package com.example.bgmachine.bgmachine.homes;

import android.app.Dialog;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.Typeface;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;

import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.GestureDetector;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.chice.scangun.ScanGun;
import com.example.bgmachine.bgmachine.ContentInfor;
import com.example.bgmachine.bgmachine.HttpsUtil;
import com.example.bgmachine.bgmachine.MainActivity;
import com.example.bgmachine.bgmachine.R;
import com.example.bgmachine.bgmachine.Urlinfor;
import com.example.bgmachine.bgmachine.clearpopups.ClearItem;
import com.example.bgmachine.bgmachine.clearpopups.ClearpupView;
import com.example.bgmachine.bgmachine.commons.CleanConfigRecord;
import com.example.bgmachine.bgmachine.commons.CleanDatabaseRecord;
import com.example.bgmachine.bgmachine.commons.CleanStatusRecord;
import com.example.bgmachine.bgmachine.commons.ConfigParams;
import com.example.bgmachine.bgmachine.commons.ImageloadView;
import com.example.bgmachine.bgmachine.databases.MyDatabaseInfor;
import com.example.bgmachine.bgmachine.datas.CleanDataRecord;
import com.example.bgmachine.bgmachine.datas.CleanRunRecord;
import com.example.bgmachine.bgmachine.exts.CartDatas;
import com.example.bgmachine.bgmachine.exts.CleanRecordData;
import com.example.bgmachine.bgmachine.exts.DevicesInfors;
import com.example.bgmachine.bgmachine.exts.SlovmeData;
import com.example.bgmachine.bgmachine.goods.GoodFragment;
import com.example.bgmachine.bgmachine.goods.HomepageGridRightMenuItemData;
import com.example.bgmachine.bgmachine.goods.HomepageLeftMenuItemData;
import com.example.bgmachine.bgmachine.handlouts.HandlContentData;
import com.example.bgmachine.bgmachine.handlouts.HandloutFragment;
import com.example.bgmachine.bgmachine.logins.LoginViews;
import com.example.bgmachine.bgmachine.logs.DebugUtils;
import com.example.bgmachine.bgmachine.martirelpro.HomepageMertrielProgressAdapter;
import com.example.bgmachine.bgmachine.martirelpro.HomepageMertrielProgressItemData;
import com.example.bgmachine.bgmachine.medias.CustomVideoView;
import com.example.bgmachine.bgmachine.modbus.ByteUtils;
import com.example.bgmachine.bgmachine.modbus.ModbusUtils;
import com.example.bgmachine.bgmachine.orders.OrderContentData;
import com.example.bgmachine.bgmachine.orders.OrderFragment;
import com.example.bgmachine.bgmachine.paycode.PayCodes;
import com.example.bgmachine.bgmachine.popupviews.AbnormalTemperatureView;
import com.example.bgmachine.bgmachine.popupviews.CleanCompulsoryView;
import com.example.bgmachine.bgmachine.popupviews.CleanReminderView;
import com.example.bgmachine.bgmachine.popupviews.PasswrdSetdialog;
import com.example.bgmachine.bgmachine.popupviews.TeaMachineWaitViews;
import com.example.bgmachine.bgmachine.produces.ProducePopupView;
import com.example.bgmachine.bgmachine.produces.ScancodePopupView;
import com.example.bgmachine.bgmachine.serialport.SerialPortScanUtils;
import com.example.bgmachine.bgmachine.serialport.SerialPortTeaMachineUtils;
import com.example.bgmachine.bgmachine.serialport.SerialPortUtils;
import com.example.bgmachine.bgmachine.serialport.SerialPortWeightUtils;
import com.example.bgmachine.bgmachine.sets.CheckSetData;
import com.example.bgmachine.bgmachine.sets.SetsFragment;
import com.example.bgmachine.bgmachine.specifs.SpecifData;
import com.example.bgmachine.bgmachine.specifs.SpecifPopuView;
import com.example.bgmachine.bgmachine.waitviews.WeiboDialogUtils;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttTopic;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;

import android_serialport_api.SerialPort;

public class HomePages extends AppCompatActivity {


    private boolean mIsVirtual = false; //true

    private LinearLayout homepages_background_layout_linearlayout_one = null;
    private RelativeLayout homepages_background_layout_linearlayout_two = null;
    private RelativeLayout  homepages_background_layout_linearlayout_three = null;
    private RelativeLayout home_page_top_relativelayout = null;
    private ImageView home_page_top_imageview = null;


    private CustomVideoView mCustomVideoView = null;
    private TreeSet<String> msetcontents = new TreeSet<>();

    private String mdirName = "";
    private String mdirFileName = "";
    private String mdirFileTextName = "";

    private int mindex = 0;

    private Button main_model_change_btn = null;
    private boolean device_model_status = false;

    private PasswrdSetdialog mPasswrdSetdialog = null;
    private static final int SCREEN_ERROR = 1;
    private static final int SCREEN_LOGIN = 6;
    private static final int LOGIN_ERROR = 7;

    private String m_typeOrder;
    private String m_typeinfor;
    private String m_names ="";
    private boolean misSend = false;

    private boolean mIsCancels = false;
    //设备类型

    private LoginViews mLoginViews = null;

    private int m_select_types = 0;
    private int m_select_current_types = 0;
    private int m_select_current_runs = 0;

    private String m_userNames = "";
    private String m_userPwds = "";
    public Handler handlerLogins = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Log.d("aaaaa", "ccccc: ");
            switch (msg.what) {
                case SCREEN_LOGIN:
                    if (mWeiboDialog != null) {
                        WeiboDialogUtils.closeDialog(mWeiboDialog);

                    }
                    String responsf = (String) msg.obj;
                    Log.d("aaaaa", "responsf=1=" + responsf);

                    try {
                        JSONObject jsonObject = new JSONObject(responsf);
                        boolean status = jsonObject.optBoolean("status");
                        if (!status) {
                            //   mError = mContext.getResources().getString(R.string.main_local_device_error_three);
                            // mtxtErrorTip.setText(mContext.getResources().getString(R.string.main_local_device_two) + mError);
                            //   mtxtErrorTip.setVisibility(TextView.VISIBLE);
                            Toast.makeText(mContext, mContext.getResources().getString(R.string.main_local_device_error_three), Toast.LENGTH_SHORT).show();
                        } else {
                            JSONObject rows = jsonObject.optJSONObject("rows");
                            int pers = rows.optInt("pers");
                            // pers=1;
                            if (pers == 1) {
                                handlDeviceType();
                                return;
                            } else {
//                               mError = mContext.getResources().getString(R.string.main_local_device_error_four);
//                               mtxtErrorTip.setText(mContext.getResources().getString(R.string.main_local_device_two) + mError);
//                               mtxtErrorTip.setVisibility(TextView.VISIBLE);
                                Toast.makeText(mContext, mContext.getResources().getString(R.string.main_local_device_error_four), Toast.LENGTH_SHORT).show();
                            }
                        }
                        m_select_current_runs = 1;
                        homepage_nav_top_radioGroup.check(m_select_current_types);

                    } catch (JSONException e) {
                        e.printStackTrace();

                    }
                    break;
                default:
                    break;
            }
        }
    };

    //称重检测
    private boolean mCheckWeighStatus = false;
    private boolean mCheckWeighNew = false;
    private int mCheckWeighSelects = 0;
    //称重校验
    private HashMap<String, Float> moutmaterialsSpeedMap = new HashMap<String, Float>();
    private HashMap<String, Integer> moutmaterialsTimesMap = new HashMap<String, Integer>();
    private HashMap<String, Integer> moutmaterialsNumsMap = new HashMap<String, Integer>();
    private HashMap<String, Integer> mmenumaterialsNumsMap = new HashMap<String, Integer>();
    private ArrayList<JSONArray> moutmaterialsArrys = new ArrayList<JSONArray>();
    private ArrayList<String> moutListArrys = new ArrayList<String>();

    private JSONArray moutmaterialsInfors = new JSONArray();
    private String mtypeOrder = "";
    private String moutmaterialsNames = "";

    private int mOutCurrentWeighs1 = 0;
    private int mOutCurrentWeighs2 = 0;
    private int mOutCurrentAllWeighs = 0;
    private int mOutCurrentWeighsInits = 0;
    private int mOutCurrentAllTimesWeighs = 0;

    private CleanReminderView mCleanReminderView = null;
    private CleanCompulsoryView mCleanCompulsoryView = null;

    private CleanRunThread mCleanRunThread = new CleanRunThread();

    private Handler mTimeHandlerCleanOne = new Handler() {
        public void handleMessage(android.os.Message msg) {

            mTimeHandlerCleanOne.removeMessages(304);
            mCleanRunThread = new CleanRunThread();
            mCleanRunThread.start();
            //  HashMap<String, CleanRunRecord> cleanRunRecordMap = CleanConfigRecord.getmUrlinfor().getmCleanRunRecordMap();
            //  CleanDatabaseRecord
            mTimeHandlerCleanOne.sendEmptyMessageDelayed(304, 5 * 60 * 1000); //5 * 60 * 1000

        }
    };

    private int mCurrentWeighTypes = 0;
    private int mCurrentWeighs1 = 0;
    private int mCurrentWeighs2 = 0;
    private int mCurrentAllWeighs = 0;
    private int mCurrentWeighsInits = 0;
    private int mCurrentWeighsBumbers = 0;
    private Handler mTimeHandlerWeighOne = new Handler() {
        public void handleMessage(android.os.Message msg) {

            mTimeHandlerWeighOne.removeMessages(300);
            mCurrentWeighsInits = 0;
            getWeight();

            // mTimeHandlerWeighOne.sendEmptyMessageDelayed(300, 300);
        }
    };
    private Handler mTimeHandlerWeighTwo = new Handler() {
        public void handleMessage(android.os.Message msg) {

            mTimeHandlerWeighTwo.removeMessages(301);
            if (mIsCancels) {
                return;
            }

//            if (mCurrentAllWeighs >= 5000) {
//                Toast.makeText(mContext, mContext.getResources().getString(R.string.home_page_weight_error_three), Toast.LENGTH_SHORT).show();
//
//            } else {
            if (mCurrentWeighsInits == 0) {
                Log.d(TAG, "handleMessage: ==1=");
                mCurrentWeighs1 = mCurrentAllWeighs;
                mCurrentWeighsInits = 1;
                Log.d(TAG, "handleMessage: ==2=");

                    // mpinsWeighEmptynfors
                    HashMap<Integer, Integer> pinsEmptynfora = new HashMap<Integer, Integer>();
                    Log.d(TAG, "handleMessage: ==3=");

                    for (int kyes : mpinsWeighEmptynfors.keySet()) {
                        mCurrentWeighsBumbers = kyes;
                        pinsEmptynfora.put(kyes, 5 * 1000 * 60);
                        Log.d(TAG, "handleMessage: ==4=" + kyes);

                        break;
                    }

                    Log.d(TAG, "handleMessage5=");

                    int times = outUpData(pinsEmptynfora);

                    try {

                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    if (mProducePopupView == null) {
                        mProducePopupView = new ProducePopupView(mContext);
                    }
                    mProducePopupView.show();

                    mProducePopupView.setRunTime(times / 1000);
                    Log.d(TAG, "handleMessage5=7=");

                    getWeight();
                    Log.d(TAG, "handleMessage5=6=");

                    return;
                }
                if (mCurrentWeighsInits == 1) {
                    mCurrentWeighs2 = mCurrentAllWeighs;
                    Log.d(TAG, "handleMessage5=10=");

                    int currentWeighs = mCurrentWeighs2 - mCurrentWeighs1;
                    int currentWeigha = mpinsWeighEmptynfors.get(mCurrentWeighsBumbers);
                    if (currentWeighs >= currentWeigha) {
                        Log.d(TAG, "handleMessage5=11=");

                        mpinsWeighEmptynfors.remove(mCurrentWeighsBumbers);
                        mCurrentWeighsInits = 2;
                        cancelWeighOut();
                        if (mpinsWeighEmptynfors.size() > 0) {
                            Log.d(TAG, "handleMessage5=12=");

                            mTimeHandlerWeighOne.sendEmptyMessageDelayed(300, 300);
                            Log.d(TAG, "handleMessage5=13=");

                        } else {
                            Log.d(TAG, "handleMessage5=14=");

                            if (mProducePopupView == null) {
                                mProducePopupView = new ProducePopupView(mContext);
                            }
                            Log.d(TAG, "handleMessage5=15=");

                            mProducePopupView.dismiss();
                        }
                    } else {
                        Log.d(TAG, "handleMessage5=16=");

                        getWeight();
                        Log.d(TAG, "handleMessage5=17=");

                    }
                    //mCurrentWeighsInits = 1;

                    return;
                }
          //  }


            // mTimeHandlerWeighTwo.sendEmptyMessageDelayed(301, 300);
        }
    };
    private Handler mTimeHandlerWeighThree = new Handler() {
        public void handleMessage(android.os.Message msg) {

            mTimeHandlerWeighThree.removeMessages(302);
//            if (mCurrentAllWeighs >= 5000) {
//                Toast.makeText(mContext, mContext.getResources().getString(R.string.home_page_weight_error_three), Toast.LENGTH_SHORT).show();
//
//            } else {

                Log.d(TAG, "onDataReceive: mCurrentTypes=1=" + mCurrentTypes);
                Log.d(TAG, "onDataReceive: mOutCurrentWeighsInits=1=" + mOutCurrentWeighsInits);

                if (moutmaterialsArrys.size() > 0) {

                    Log.d(TAG, "onDataReceive: mCurrentTypes=2=" + mCurrentTypes);

                    if (mOutCurrentWeighsInits == 0) {
                        mOutCurrentWeighs1 = mCurrentAllWeighs;
                        mOutCurrentWeighsInits = 1;
                        String typeinfor = "";
                        if (moutmaterialsArrys.size() > 0) {
                            typeinfor = moutmaterialsArrys.get(0).toString();
                        }

                        Log.d(TAG, "handleMessage: typeinfor=" + typeinfor);
                        int times = outData("1", typeinfor);
                        mOutCurrentAllTimesWeighs = times;
                        try {

                            Thread.sleep(200);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                        if (mProducePopupView == null) {
                            mProducePopupView = new ProducePopupView(mContext);
                        }

                        mProducePopupView.show();
                        //   mProducePopupView.setNameInfor(names);
                        mProducePopupView.setRunTime(times / 1000);

                        mTimeSalesTime.sendEmptyMessageDelayed(TIME_SALES_DELATE, 1000);

                        return;
                    }

                    if (mOutCurrentWeighsInits == 1) {
                        Log.d(TAG, "handleMessage: mOutCurrentWeighsInits=" + mOutCurrentWeighsInits);
                        mOutCurrentWeighs2 = mCurrentAllWeighs;
                        mOutCurrentWeighsInits = 2;
                        float currentWeighas = mOutCurrentWeighs2 - mOutCurrentWeighs1;
                        float outCurrentAllTimesWeighsa = (float) (mOutCurrentAllTimesWeighs / 1000.0);
                        float speedsba = (float) currentWeighas / outCurrentAllTimesWeighsa;
                        Log.d(TAG, "handleMessage=1=: speedsba=" + speedsba);
                        Log.d(TAG, "handleMessage=1=: speedsba=" + speedsba);

                        String typeinfora = "";
                        if (moutmaterialsArrys.size() > 0) {
                            typeinfora = moutmaterialsArrys.get(0).toString();
                        }
                        try {
                            JSONArray arrycsall = new JSONArray(typeinfora);
                            int pina1 = 0;
                            int outdataa = 0;
                            for (int indexa = 0; indexa < arrycsall.length(); indexa++) {
                                JSONObject itema = arrycsall.getJSONObject(indexa);
                                int baseid = Integer.parseInt(itema.optString("materialpines"));

                                int outdata = Integer.parseInt(itema.optString("setbeverageOutput"));
                                pina1 = baseid;
                                outdataa = outdata;
                                break;
                            }
                            String inforta = String.valueOf(SlovmeData.getSlovmeData().getTypea().getTypeid()) + "-" + String.valueOf(pina1) + "-" + String.valueOf(outdataa);
                            long currentTime = System.currentTimeMillis();
                            long allTimes1 = currentTime / 1000;
                            int allTime = (int) allTimes1;
                            Log.d(TAG, "handleMessage: allTime=" + allTime);

                            String timeNow = new SimpleDateFormat("HH:mm:ss").format(currentTime);
                            moutmaterialsSpeedMap.put(inforta, speedsba);
                            moutmaterialsTimesMap.put(inforta, allTime);
                            Integer nums = moutmaterialsNumsMap.get(inforta);
                            nums++;
                            moutmaterialsTimesMap.put(inforta, nums);
                            handlOutmaterials(SlovmeData.getSlovmeData().getTypea().getTypeid(), pina1, outdataa, speedsba, allTime, nums);

                            moutmaterialsArrys.remove(0);
                            if (moutmaterialsArrys.size() > 0) {
                                mOutCurrentWeighsInits = 0;
                                getWeight();
                            } else {
                                if (mProducePopupView == null) {
                                    mProducePopupView = new ProducePopupView(mContext);
                                }

                                mProducePopupView.dismiss();
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }


                        return;
                    }
                } else {
                    if (mCheckWeighStatus) {


                        if (mOutCurrentWeighsInits == 0) {
                            mOutCurrentWeighs1 = mCurrentAllWeighs;
                            mOutCurrentWeighsInits = 1;
                            int times = outData(mtypeOrder, moutmaterialsInfors.toString());
                            try {

                                Thread.sleep(200);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }

                            if (mProducePopupView == null) {
                                mProducePopupView = new ProducePopupView(mContext);
                            }

                            mProducePopupView.show();
                            mProducePopupView.setNameInfor(moutmaterialsNames);
                            mProducePopupView.setRunTime(times / 1000);

                            mTimeSalesTime.sendEmptyMessageDelayed(TIME_SALES_DELATE, 1000);

                            return;
                        }
                        if (mOutCurrentWeighsInits == 1) {
                            mOutCurrentWeighs2 = mCurrentAllWeighs;
                            mOutCurrentWeighsInits = 2;
                            float currentWeighas = mOutCurrentWeighs2 - mOutCurrentWeighs1;
                            Log.d(TAG, "handleMessage: currentWeighas=" + currentWeighas);
                            int errorData = Integer.parseInt(SlovmeData.getSlovmeData().getTypea().getErrorData());
                            Log.d(TAG, "handleMessage: errorData=" + errorData);
                            Log.d(TAG, "handleMessage: mOutCurrentAllWeighs=" + mOutCurrentAllWeighs);

                            boolean isClear = false;
                            if (currentWeighas < (mOutCurrentAllWeighs - errorData)) {
                                Toast.makeText(mContext, mContext.getResources().getString(R.string.home_page_weight_error_four), Toast.LENGTH_SHORT).show();
                                isClear = true;
                            }
                            if (currentWeighas > (mOutCurrentAllWeighs + errorData)) {
                                Toast.makeText(mContext, mContext.getResources().getString(R.string.home_page_weight_error_five), Toast.LENGTH_SHORT).show();
                                isClear = true;
                            }
                            if (!isClear) {
                                if (mProducePopupView == null) {
                                    mProducePopupView = new ProducePopupView(mContext);
                                }
                                mProducePopupView.dismiss();
                                return;
                            }
                            long currentTime = System.currentTimeMillis();
                            long ssallTimes = currentTime / 1000;

                            Log.d(TAG, "handleMessage: ssallTimes=" + ssallTimes);
                            Integer nums = 1;
                            Log.d(TAG, "handleMessage: moutListArrys=" + moutListArrys);
                            Log.d(TAG, "handleMessage: moutListArrys.size()=" + moutListArrys.size());

                            for (int ma = 0; ma < moutListArrys.size(); ma++) {
                                String inforta = moutListArrys.get(ma);
                                Log.d(TAG, "handleMessage: inforta=" + inforta);

                                float speedsba = moutmaterialsSpeedMap.get(inforta);
                                Log.d(TAG, "handleMessage: speedsba=" + speedsba);

                                moutmaterialsTimesMap.put(inforta, (int) ssallTimes);

                                moutmaterialsTimesMap.put(inforta, nums);
                                Log.d(TAG, "handleMessage: inforta=" + inforta);

                                String[] lista = inforta.split("-");
                                Log.d(TAG, "handleMessage: lista.length=" + lista.length);

                                if (lista.length >= 3) {
                                    Log.d(TAG, "handleMessage: lista[0]=" + lista[0]);
                                    Log.d(TAG, "handleMessage: lista[1]=" + lista[1]);
                                    Log.d(TAG, "handleMessage: lista[2]=" + lista[2]);

                                    handlOutmaterials(Integer.parseInt(lista[0]), Integer.parseInt(lista[1]), Integer.parseInt(lista[2]), speedsba, (int) ssallTimes, nums);
                                }
                                if (mProducePopupView == null) {
                                    mProducePopupView = new ProducePopupView(mContext);
                                }
                                mProducePopupView.dismiss();
                                return;
                            }

                            return;
                        }
                    }

                }
        //    }

        }
    };

    private Handler mTimeHandlerWeighfour = new Handler() {
        public void handleMessage(android.os.Message msg) {

            mTimeHandlerWeighfour.removeMessages(303);
            mCurrentWeighsInits = 0;
            getWeight();
        }
    };
    private int mCurrentTypes = 0;
    private int mEmptyType = 0;
    private HashMap<Integer, Integer> mpinsTimesEmptynfors = new HashMap<Integer, Integer>();
    private HashMap<Integer, Integer> mpinsWeighEmptynfors = new HashMap<Integer, Integer>();
    private ImageloadView top_logo_image_load = null;
    //物联网处理
    private static final int CONNECT_SUCCESS = 2;
    private static final int CONNECT_FAILURE = 3;
    private static final int CONNECT_CONTENT = 4;
    private static final int CONNECT_CMD = 5;
    private static final int CONNECT_DEVICE_STATUS = 10;
    private static final int CHANGE_START = 6;
    private static final int RECONECT_DATA = 7;
    private static final int CHCKACOUNT_DATA = 8;
    private static final int LOCAL_DEL_DATA = 9;
    private static final int CONTENT_DATA_ONE = 30;
    private static final int CONTENT_DATA_TWO = 31;
    private static final int CONTENT_DATA_THREE = 32;
    private static final int CONTENT_DATA_FOUR = 33;
    private static final int CONTENT_DATA_FIVE = 34;
    private static final int CONTENT_DATA_SIX = 35;
    private static final int CONTENT_DATA_SEVEN = 36;

    private static final int CONNECT_RECT_DATA = 20;

    private static final int TIME_ERROR_VIEW = 0x230;

    private static final int TIME_SECOND_VIEW = 0x235;
    private static final int TIME_QM_SALES_DELATE = 0x231;
    private static final int TIME_SALES_DELATE = 0x232;
    private static final int TIME_ERROR_DIS_VIEW = 0x233;

    public static HomePages mHomePages = null; //定义一个本类型的成员变量
    private static String TAG = "HomePages";
    private static int TIME_CHECKED_BUTTON = 600;
    public String mSourcePaths = "";
    public HashMap<String, Bitmap> mloadImage = new HashMap<String, Bitmap>();
    public TextView home_page_time_text = null; //显示时间
    private Button home_page_time_btn = null;
    private int lastClickTime = 0;

    private Handler mTimeHandlerClickTime = new Handler() {
        public void handleMessage(android.os.Message msg) {

            mTimeHandlerClickTime.removeMessages(1001);
            // lastClickTime = 0;

            if (lastClickTime > 2) {
                fullyRestartApp(mContext);
            }
            lastClickTime = 0;
        }
    };

    private static final int DOUBLE_CLICK_TIME_DELTA = 300; // 双击间隔时间(毫秒)

    //进度
    public ProducePopupView mProducePopupView = null;
    public ScancodePopupView mScancodePopupView = null;
    //选择规格
    public SpecifPopuView mSpecifPopuView = null;
    public List<SpecifData> mSpecifData = new LinkedList<SpecifData>();
    public String mOutInfors ="";


    //弹窗
    public ClearpupView mClearpupView = null;
    public HomepageMertrielProgressAdapter mHomepageMertrielProgressAdapter = null;
    public GridView homepages_martirel_layout_text_progress = null; //按钮

    //等待界面
    private Dialog mWeiboDialog = null;

    //茶机
    private TeaMachineWaitViews mTeaMachineWaitViews = null;
    private AbnormalTemperatureView mAbnormalTemperatureView = null;

    private SerialPortTeaMachineUtils mSerialPortTeaMachineUtils = new SerialPortTeaMachineUtils();
    private SerialPort mSerialPortTeaMachinePort = null;
    private byte[] mBuffTeaMachineStr = new byte[1024 * 3];
    private int m_curTeaMachineLength = 0;
    private int m_curTeaMachineNumbers = 0;
    private ArrayList<Integer> moutTeaMachineArrys = new ArrayList<Integer>();
    private int[] crcPolynomTable =
            {
                    0x0000, 0xc0c1, 0xc181, 0x0140, 0xc301, 0x03c0, 0x0280, 0xc241,
                    0xc601, 0x06c0, 0x0780, 0xc741, 0x0500, 0xc5c1, 0xc481, 0x0440,
                    0xcc01, 0x0cc0, 0x0d80, 0xcd41, 0x0f00, 0xcfc1, 0xce81, 0x0e40,
                    0x0a00, 0xcac1, 0xcb81, 0x0b40, 0xc901, 0x09c0, 0x0880, 0xc841,
                    0xd801, 0x18c0, 0x1980, 0xd941, 0x1b00, 0xdbc1, 0xda81, 0x1a40,
                    0x1e00, 0xdec1, 0xdf81, 0x1f40, 0xdd01, 0x1dc0, 0x1c80, 0xdc41,
                    0x1400, 0xd4c1, 0xd581, 0x1540, 0xd701, 0x17c0, 0x1680, 0xd641,
                    0xd201, 0x12c0, 0x1380, 0xd341, 0x1100, 0xd1c1, 0xd081, 0x1040,
                    0xf001, 0x30c0, 0x3180, 0xf141, 0x3300, 0xf3c1, 0xf281, 0x3240,
                    0x3600, 0xf6c1, 0xf781, 0x3740, 0xf501, 0x35c0, 0x3480, 0xf441,
                    0x3c00, 0xfcc1, 0xfd81, 0x3d40, 0xff01, 0x3fc0, 0x3e80, 0xfe41,
                    0xfa01, 0x3ac0, 0x3b80, 0xfb41, 0x3900, 0xf9c1, 0xf881, 0x3840,
                    0x2800, 0xe8c1, 0xe981, 0x2940, 0xeb01, 0x2bc0, 0x2a80, 0xea41,
                    0xee01, 0x2ec0, 0x2f80, 0xef41, 0x2d00, 0xedc1, 0xec81, 0x2c40,
                    0xe401, 0x24c0, 0x2580, 0xe541, 0x2700, 0xe7c1, 0xe681, 0x2640,
                    0x2200, 0xe2c1, 0xe381, 0x2340, 0xe101, 0x21c0, 0x2080, 0xe041,
                    0xa001, 0x60c0, 0x6180, 0xa141, 0x6300, 0xa3c1, 0xa281, 0x6240,
                    0x6600, 0xa6c1, 0xa781, 0x6740, 0xa501, 0x65c0, 0x6480, 0xa441,
                    0x6c00, 0xacc1, 0xad81, 0x6d40, 0xaf01, 0x6fc0, 0x6e80, 0xae41,
                    0xaa01, 0x6ac0, 0x6b80, 0xab41, 0x6900, 0xa9c1, 0xa881, 0x6840,
                    0x7800, 0xb8c1, 0xb981, 0x7940, 0xbb01, 0x7bc0, 0x7a80, 0xba41,
                    0xbe01, 0x7ec0, 0x7f80, 0xbf41, 0x7d00, 0xbdc1, 0xbc81, 0x7c40,
                    0xb401, 0x74c0, 0x7580, 0xb541, 0x7700, 0xb7c1, 0xb681, 0x7640,
                    0x7200, 0xb2c1, 0xb381, 0x7340, 0xb101, 0x71c0, 0x7080, 0xb041,
                    0x5000, 0x90c1, 0x9181, 0x5140, 0x9301, 0x53c0, 0x5280, 0x9241,
                    0x9601, 0x56c0, 0x5780, 0x9741, 0x5500, 0x95c1, 0x9481, 0x5440,
                    0x9c01, 0x5cc0, 0x5d80, 0x9d41, 0x5f00, 0x9fc1, 0x9e81, 0x5e40,
                    0x5a00, 0x9ac1, 0x9b81, 0x5b40, 0x9901, 0x59c0, 0x5880, 0x9841,
                    0x8801, 0x48c0, 0x4980, 0x8941, 0x4b00, 0x8bc1, 0x8a81, 0x4a40,
                    0x4e00, 0x8ec1, 0x8f81, 0x4f40, 0x8d01, 0x4dc0, 0x4c80, 0x8c41,
                    0x4400, 0x84c1, 0x8581, 0x4540, 0x8701, 0x47c0, 0x4680, 0x8641,
                    0x8201, 0x42c0, 0x4380, 0x8341, 0x4100, 0x81c1, 0x8081, 0x4040
            };
    //称重串口
    private SerialPortWeightUtils mSerialPortWeightUtils = new SerialPortWeightUtils();
    private SerialPort mSerialWeightPort = null;
    private byte[] mBuffWeightStr = new byte[1024 * 3];
    private int m_currenLengt = 0;

    private int mCurrentRunStatus = 0;
    private int mInitWeight = 0;
    private int mEndWeight = 0;
    private int mCurrentPins = 0;
    private EditText mcheck_input_edittext = null;
    private CheckSetData mcheckSetData = null;
    //扫描二维码
    private SerialPortScanUtils mSerialPortScanUtils = new SerialPortScanUtils();
    private SerialPort mSerialScanPort = null;
    private byte[] mBuffScanStr = new byte[1024 * 3];
    private int m_AllScanLength = 0;
    //串口
    private SerialPortUtils mSerialPortUtils = new SerialPortUtils();
    private SerialPort mSerialPort = null;
    private byte[] mBuffStr = new byte[1024 * 3];
    private int m_AllLength = 0;
    private int m_frame_id = 1;
    private Handler mTimeHandlerCmdOne = new Handler() {
        public void handleMessage(android.os.Message msg) {

            mTimeHandlerCmdOne.removeMessages(500);
            if (mIsCancels) {
                return;
            }
            if (mCurrentTypes == 3 || mCurrentTypes == 4) {
                Log.d(TAG, "handleMessage: ==1");
                HashMap<Integer, Integer> pinsEmptynfora = new HashMap<Integer, Integer>();
                Log.d(TAG, "handleMessage: ==2");

                if (mpinsTimesEmptynfors.size() > 0) {
                    if (mpinsTimesEmptynfors.size() > 12) {
                        int numna = 0;
                        ArrayList<Integer> listas1 = new ArrayList<Integer>();
                        Log.d(TAG, "handleMessage: ==3");

                        for (int kyes : mpinsTimesEmptynfors.keySet()) {
                            pinsEmptynfora.put(kyes, mpinsTimesEmptynfors.get(kyes));
                            numna++;
                            listas1.add(kyes);
                            Log.d(TAG, "handleMessage: ==4");

                            //    mpinsTimesEmptynfors.remove(kyes);
                            if (numna >= 6) {
                                Log.d(TAG, "handleMessage: ==5");

                                break;
                            }
                            Log.d(TAG, "handleMessage: ==6");

                        }
                        Log.d(TAG, "handleMessage: ==7");

                        for (int i = 0; i < listas1.size(); i++) {
                            int itema1 = listas1.get(i);
                            Log.d(TAG, "handleMessage: ==7=" + itema1);

                            mpinsTimesEmptynfors.remove(itema1);
                        }

                    } else {
                        Log.d(TAG, "handleMessage: ==8");

                        for (int kyes : mpinsTimesEmptynfors.keySet()) {
                            Log.d(TAG, "handleMessage: ==9");

                            pinsEmptynfora.put(kyes, mpinsTimesEmptynfors.get(kyes));
                        }
                        Log.d(TAG, "handleMessage: ==10");

                        mpinsTimesEmptynfors.clear();
                    }
                    Log.d(TAG, "handleMessage: ==11");

                    int times = outUpData(pinsEmptynfora);
                    Log.d(TAG, "handleMessage: ==12");

                    try {

                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    if (mProducePopupView == null) {
                        mProducePopupView = new ProducePopupView(mContext);
                    }
                    mProducePopupView.show();
                    //  mProducePopupView.setNameInfor(names);
                    mProducePopupView.setRunTime(times / 1000);
                    allowanceViewUpdae();
                    Log.d(TAG, "handleMessage: ==13");

                } else {
                    Log.d(TAG, "handleMessage: ==14");

                    if (mpinsWeighEmptynfors.size() > 0) {
                        //  mCurrentWeighsInits = 0;
                        //  getWeight();
                        mTimeHandlerWeighfour.sendEmptyMessageDelayed(303, 200);
                        Log.d(TAG, "handleMessage: ==15");

                    } else {
                        Log.d(TAG, "handleMessage: ==16");

                        if (mProducePopupView != null) {
                            mProducePopupView.closeView();
                        }
                    }
                    Log.d(TAG, "handleMessage: ==17");

                }


            } else {
                if (moutmaterialsArrys.size() > 0) {
                    Log.d(TAG, "handleMessage: mCurrentTypes=" + mCurrentTypes);
                    Log.d(TAG, "handleMessage: moutmaterialsArrys.size()=" + moutmaterialsArrys.size());

                    if (mCurrentTypes == 1) {
                        getWeight();
                    } else {
                        if (mProducePopupView != null) {
                            mProducePopupView.closeView();
                        }
                    }

                } else {
                    if (mCheckWeighStatus) {

                        getWeight();
                    } else {

                        if (mProducePopupView != null) {
                            mProducePopupView.closeView();
                        }
                    }

                }


            }


        }
    };
    //数据库
    private MyDatabaseInfor myDatabaseInfor = null;
    private SQLiteDatabase mBdread = null;
    private SQLiteDatabase mBdwrite = null;
    private Context mContext = null;
    private TextView mtxtVersionTip = null;
    private TextView mtxtErrorTip = null;
    private RelativeLayout home_gae_error_rlativeLayout = null;
    private ArrayList<HomepageMertrielProgressItemData> mHomepageMertrielProgressItemData = new ArrayList<HomepageMertrielProgressItemData>();
    private HashMap<Integer, Integer> mpinsUserInfors = new HashMap<Integer, Integer>();
    private LinkedHashMap<Integer, String> mPinsNames = new LinkedHashMap<Integer, String>();
    private HashMap<Integer, Float> mPinsSpeeds = new HashMap<Integer, Float>();
    private HashMap<Integer, MerilData> mPinsMerilData = new HashMap<Integer, MerilData>();
    private Map<String, Integer> materialsCapacity = new HashMap<>();
    private Map<Integer, Integer> materialsNumsCapacity = new HashMap<>();

    private Map<Integer , Integer> materialsPins = new HashMap<>();

    private ArrayList<Integer> mPinsShortage = new ArrayList<Integer>();
    private HashMap<Integer, Integer> mMaterielQualitativeLen = new HashMap<Integer, Integer>();
    private HashMap<Integer, Integer> mPinsReala = new HashMap<Integer, Integer>();
    private Handler mCheckedTime = new Handler() {
        public void handleMessage(android.os.Message msg) {
            mCheckedTime.removeMessages(TIME_CHECKED_BUTTON);
            if (mCurrentRunStatus == 0) {
                WeiboDialogUtils.closeDialog(mWeiboDialog);
                Toast.makeText(mContext, mContext.getResources().getString(R.string.home_page_weight_error_one), Toast.LENGTH_SHORT).show();

            } else {
                if (mCurrentRunStatus == 1) {
                    mCurrentRunStatus = 2;
                    int times = 0;
                    handPinTimes(mCurrentPins);
                    times += 5000;
                    mCheckedTime.sendEmptyMessageDelayed(TIME_CHECKED_BUTTON, times);
                } else {

                    if (mCurrentRunStatus == 2) {
                        getWeight();
                        mCheckedTime.sendEmptyMessageDelayed(TIME_CHECKED_BUTTON, 2000);
                    } else {

                        if (mCurrentRunStatus == 3) {
                            float weights = mEndWeight - mInitWeight;
                            weights = weights / 3;
                            DecimalFormat decimalFormat = new DecimalFormat("#0.00");

                            // 调用format()方法进行格式化
                            String formattedNumber = decimalFormat.format(weights);

                            mcheck_input_edittext.setText(formattedNumber);
                            mcheckSetData.setSpeedInfor(weights);
                        } else {
                            Toast.makeText(mContext, mContext.getResources().getString(R.string.home_page_weight_error_two), Toast.LENGTH_SHORT).show();

                        }
                        WeiboDialogUtils.closeDialog(mWeiboDialog);
                    }

                }

            }

            //  mCurrentSeekBar.setProgress(567);


        }
    };
    private Handler mTimeHandlerCmdTwo = new Handler() {
        public void handleMessage(android.os.Message msg) {

            mTimeHandlerCmdTwo.removeMessages(501);
            if (mIsCancels) {
                return;
            }
            if (mClearpupView != null) {
                mClearpupView.sendClearCmd();
            }

//            if (mProducePopupView != null) {
//                mProducePopupView.closeView();
//            }

        }
    };
    private UserDataThread mUserDataThread = new UserDataThread();
    //扫描
    private Switch home_page_switch_button = null;
    private ScanGun mScanGun = null;
    private boolean mCurrentisScan = true;
    private boolean isHandleKey = false;
    private RadioGroup homepage_nav_top_radioGroup = null;
    private RadioButton homepage_nav_top_goods_radiobtn = null;
    private RadioButton homepage_nav_top_order_radiobtn = null;
    private RadioButton homepage_nav_top_handl_out_radiobtn = null;
    private RadioButton homepage_nav_top_set_radiobtn = null;
    private FrameLayout home_page_content = null;
    private GoodFragment fg1 = null;
    private OrderFragment fg2 = null;
    public Handler mMqttRectHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Log.d("aaaaa", "ccccc: ");
            //   Toast.makeText(mContext, "myTopic myTopic="+myTopic , Toast.LENGTH_SHORT).show();
            switch (msg.what) {

                case CONNECT_RECT_DATA:
                    String str1 = (String) msg.obj;

                    handlReconnetData(str1);
                    break;
                default:
                    break;
            }
        }
    };
    private HandloutFragment fg3 = null;
    private SetsFragment fg4;
    private FragmentManager fManager = null;
    private boolean mqtt_link_state = false;

    private Handler mTimeErrorDisView = new Handler() {
        public void handleMessage(android.os.Message msg) {

            mTimeErrorDisView.removeMessages(TIME_ERROR_DIS_VIEW);

            if (home_gae_error_rlativeLayout != null) {
                String errors = mContext.getResources().getString(R.string.main_local_device_error_one);
                home_gae_error_rlativeLayout.setVisibility(RelativeLayout.VISIBLE);

                mtxtErrorTip.setText(mContext.getResources().getString(R.string.main_local_device_two) + errors);
                // mtxtErrorTip.setVisibility(TextView.VISIBLE);
                // return;
            }


        }
    };
    private MqttClient client;
    private String host = Urlinfor.getmUrlinfor().getMqttHost();//服务器IP地址，如果是广域网地址，必须在路由是做端口映射！！才能外网通信
    private boolean mqIsInist = false;
    private boolean mqIsRect = false;
    private String userName = "admin";
    private String mdeiveid = "111";
    private String passWord = "admin";
    private MqttTopic topic;
    private MqttMessage mMqttmessage;
    private MqttConnectOptions options;
    private ScheduledExecutorService scheduler;
    private String myTopic = "head/";

    private HandlDataThread mHandlDataThread = new HandlDataThread();
    private HandlSendThread mHandlSendThread = new HandlSendThread();

    private Handler mTimeSecondView = new Handler() {
        public void handleMessage(android.os.Message msg) {
            mTimeSecondView.removeMessages(TIME_SECOND_VIEW);

            if (misSend == true) {

                misSend =false;


                int times = outSecondsData( m_typeOrder, m_typeinfor);
                try {

                    Thread.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Log.d(TAG, "setProduceProgress: getWeight=9");


                if (mProducePopupView == null) {
                    mProducePopupView = new ProducePopupView(mContext);
                }
                Log.d(TAG, "setProduceProgress: getWeight=10");

                mProducePopupView.show();
                mProducePopupView.setNameInfor( m_names );
                mProducePopupView.setRunTime(times / 1000);
                Log.d(TAG, "setProduceProgress: getWeight=11");

                mTimeSalesTime.sendEmptyMessageDelayed(TIME_SALES_DELATE, 1000);
                Log.d(TAG, "setProduceProgress: getWeight=12");


            }else {
                stopTeaMachine();
            }
        }
    };

    private Handler mTimeErrorView = new Handler() {
        public void handleMessage(android.os.Message msg) {

            mTimeErrorView.removeMessages(TIME_ERROR_VIEW);
            if (home_gae_error_rlativeLayout != null) {

                home_gae_error_rlativeLayout.setVisibility(RelativeLayout.GONE);

            }
        }
    };
    public Handler mContHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case CONTENT_DATA_ONE:
                    String str1 = (String) msg.obj;

                    Log.d(TAG, "handleMessage:str1=" + str1);
                    if (mCurrentisScan) {
                        mCurrentisScan = false;
                        // homepage_scan_btn.setAlpha((float) 1.0);

                        handlScanInfor(str1);
                        //  handlAllPinInfor(Integer.valueOf(scanResult).intValue());
                    }
                    break;
                case CONTENT_DATA_TWO:
                    String str2 = (String) msg.obj;
                    if (moutTeaMachineArrys != null) {
                        moutTeaMachineArrys.clear();

                    }
                    if (mTimeFindRunSatus != null) {
                        mTimeFindRunSatus.removeMessages(1002);
                    }

                    Log.d(TAG, "handleMessage:str2=" + str2);
                    if (mTeaMachineWaitViews != null) {
                        mTeaMachineWaitViews.dismiss();
                    }

                    break;
                case CONTENT_DATA_THREE:
                    if (moutTeaMachineArrys != null) {
                        moutTeaMachineArrys.clear();

                    }
                    if (mTimeFindRunSatus != null) {
                        mTimeFindRunSatus.removeMessages(1002);
                    }
                    if (mAbnormalTemperatureView == null) {
                        mAbnormalTemperatureView = new AbnormalTemperatureView(mContext);
                    }
                    mAbnormalTemperatureView.show();
                    break;
                case CONTENT_DATA_FOUR:
                    if (moutTeaMachineArrys != null) {
                        moutTeaMachineArrys.clear();

                    }
                    if (mTimeFindRunSatus != null) {
                        mTimeFindRunSatus.removeMessages(1002);
                    }
                    if (mAbnormalTemperatureView == null) {
                        mAbnormalTemperatureView = new AbnormalTemperatureView(mContext);
                    }
                    mAbnormalTemperatureView.show();
                    break;
                case CONTENT_DATA_FIVE:
                    if (moutTeaMachineArrys != null) {
                        moutTeaMachineArrys.clear();

                    }
                    if (mTimeFindRunSatus != null) {
                        mTimeFindRunSatus.removeMessages(1002);
                    }
                    if (mAbnormalTemperatureView == null) {
                        mAbnormalTemperatureView = new AbnormalTemperatureView(mContext);
                    }
                    mAbnormalTemperatureView.show();
                    break;
            }
        }
    };

    public Handler mMqttHandler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Log.d("aaaaa", "ccccc: ");
            //   Toast.makeText(mContext, "myTopic myTopic="+myTopic , Toast.LENGTH_SHORT).show();
            switch (msg.what) {

                case CONNECT_SUCCESS:
                    Log.d("aaaaa", "ccccc333");
                    //  Toast.makeText(mContext, "CONNECT_SUCCESS=" , Toast.LENGTH_SHORT).show();
                    try {
                        //    Toast.makeText(mContext, "CONNECT_SUCCESS myTopic="+myTopic , Toast.LENGTH_SHORT).show();
                        client.subscribe(myTopic + Urlinfor.getmUrlinfor().getMysqlName(), 1);
                        client.subscribe(myTopic + Urlinfor.getmUrlinfor().getMysqlName() + Urlinfor.getmUrlinfor().getShopInformationId(), 1);
                        client.subscribe(myTopic + Urlinfor.getmUrlinfor().getMysqlName() + Urlinfor.getmUrlinfor().getMdevicenums(), 1);
                        client.subscribe(myTopic + Urlinfor.getmUrlinfor().getShopInformationId() + Urlinfor.getmUrlinfor().getMdevicenums(), 1);

                        Log.d(TAG, "currentmyTopic+mbasename=2=" + myTopic + Urlinfor.getmUrlinfor().getMysqlName());
                        Log.d(TAG, "currentmyTopic+mbasename=3=" + myTopic + Urlinfor.getmUrlinfor().getMysqlName() + Urlinfor.getmUrlinfor().getShopInformationId());
                        Log.d(TAG, "currentmyTopic+mbasename=4=" + myTopic + Urlinfor.getmUrlinfor().getMysqlName() + Urlinfor.getmUrlinfor().getMdevicenums());
                        Log.d(TAG, "currentmyTopic+mbasename=5=" + myTopic + Urlinfor.getmUrlinfor().getShopInformationId() + Urlinfor.getmUrlinfor().getMdevicenums());
                        Log.d(TAG, "currentmyTopic+mbasename=6=" + myTopic + Urlinfor.getmUrlinfor().getShopInformationId() + Urlinfor.getmUrlinfor().getMdevicenums() + "_cmd");


                        mqtt_link_state = true;
//                        if (mqIsInist) {
//                            mTimeErrorView.sendEmptyMessageDelayed(TIME_ERROR_VIEW, 800);
//                        }
                        mHandlSendThread = new HandlSendThread();
                        mHandlSendThread.start();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case CONNECT_FAILURE:
                    Log.d("aaaaa", "ccccc444");

                    mqtt_link_state = false;
//                    if (mqIsInist) {
//                        mTimeErrorDisView.sendEmptyMessageDelayed(TIME_ERROR_DIS_VIEW, 800);
//
//                    }

                    break;
                case CONNECT_CONTENT:
                    Log.d("aaaaa", "ccccc555");

                    String str1 = (String) msg.obj;

                    handlMqttData(str1);
                    break;
                case CONNECT_CMD:
                    Log.d("aaaaa", "ccccc555");

                    String str2 = (String) msg.obj;

                    handlCmdMqttData(str2);
                    break;

                case CONNECT_DEVICE_STATUS:
                    Log.d("aaaaa", "ccccc10");
                    //    Toast.makeText(getWindow().getContext(), (String) msg.obj,
                    //          Toast.LENGTH_SHORT).show();
                    String str3 = (String) msg.obj;

                    //    mDeviceList = str2;
                    //      handlMqttDeviceStatus();
                    break;

                case CHANGE_START:
                    if(false){
                        mHandlDataThread = new HandlDataThread();
                        mHandlDataThread.start();
                    }



                    break;

                case RECONECT_DATA:
                    String currentcont = (String) msg.obj;
                    handlReconnetData(currentcont);
                    break;

                case LOCAL_DEL_DATA:
                    try {
                        String currentconta = (String) msg.obj;
                        MqttMessage tempInfora = new MqttMessage();
                        tempInfora.setQos(0);
                        tempInfora.setRetained(false);
                        System.out.println(tempInfora.isRetained() + "------ratained状态");
                        tempInfora.setPayload(currentconta.getBytes());
                        //String timea,String name, String orders,String prices

                        String sendIds = myTopic + Urlinfor.getmUrlinfor().getMysqlName() + Urlinfor.getmUrlinfor().getShopInformationId();
                        client.publish(sendIds, tempInfora);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                default:
                    break;
            }
        }

    };
    private Handler mTimeSalesTime = new Handler() {
        public void handleMessage(android.os.Message msg) {

            mTimeSalesTime.removeMessages(TIME_SALES_DELATE);
            sendRequestRealTimeSalesData();
            allowanceViewUpdae();
        }
    };
    private String mTimeQmSalesInfor = "";
    private Handler mTimeQmSalesTime = new Handler() {
        public void handleMessage(android.os.Message msg) {
            mTimeQmSalesTime.removeMessages(TIME_QM_SALES_DELATE);

            sendRequestRealMqTimeSalesData();

            allowanceViewUpdae();

            updateMqSales();
            Message msga = new Message();


            msga.what = LOCAL_DEL_DATA;
            msga.obj = mTimeQmSalesInfor;
            mMqttHandler.sendMessage(msga);
        }
    };
    private Handler mTimeHandlerCmdThree = new Handler() {
        public void handleMessage(android.os.Message msg) {

            mTimeHandlerCmdThree.removeMessages(502);
            mTimeQmSalesTime.removeMessages(TIME_QM_SALES_DELATE);
            mTimeSalesTime.removeMessages(TIME_SALES_DELATE);

            String inforsa = "";
            for (int i = 0; i < mPinsShortage.size(); i++) {

                int baseid = mPinsShortage.get(i);
                for (int kyes : mPinsReala.keySet()) {
                    int relas = mPinsReala.get(kyes);
                    if (relas == baseid) {
                        MerilData merilData = mPinsMerilData.get(kyes);
                        inforsa += merilData.getMaterialName() + ";";
                    }
                }

            }

            if (mProducePopupView != null) {
                mProducePopupView.closeView();
            }
            Toast.makeText(mContext, mContext.getResources().getString(R.string.home_page_weight_error_shortage_materials) + inforsa, Toast.LENGTH_SHORT).show();


        }
    };
    private Handler mTimeShowHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    Log.d(TAG, "handleMessage: msg.what=" + msg.what);
                    mHomepageMertrielProgressAdapter.notifyDataSetChanged();
                    break;
                case 2:
                    DebugUtils.printDebugInfo("");
                    if (mCleanReminderView == null) {
                        mCleanReminderView = new CleanReminderView(mContext);
                    }
                    mCleanReminderView.show();
                    mCleanReminderView.setBtnOnClick(new View.OnClickListener() {
                        public void onClick(View v) {
                            CleanStatusRecord.getmUrlinfor().setmCleanTopStatus(0);
                            CleanRunRecord recorda = CleanStatusRecord.getmUrlinfor().getCleanRunRecord();
                            if (recorda != null) {
                                CleanRecordData.getCleanRecordData().setCleantimename(recorda.getClearName());
                                HomePages.mHomePages.setClearpupView(recorda.getClearContent());
                            }
                            mCleanReminderView.dismiss();

                        }

                    });

                    break;
                case 3:
                    DebugUtils.printDebugInfo("");
                    if (mCleanCompulsoryView == null) {
                        mCleanCompulsoryView = new CleanCompulsoryView(mContext);
                    }
                    mCleanCompulsoryView.show();
                    mCleanCompulsoryView.setBtnOnClick(new View.OnClickListener() {
                        public void onClick(View v) {
                            CleanStatusRecord.getmUrlinfor().setmCleanTopStatus(0);
                            CleanRunRecord recordb = CleanStatusRecord.getmUrlinfor().getCleanRunRecord();
                            if (recordb != null) {
                                CleanRecordData.getCleanRecordData().setCleantimename(recordb.getClearName());
                                HomePages.mHomePages.setClearpupView(recordb.getClearContent());
                            }
                            mCleanCompulsoryView.dismiss();

                        }

                    });
                    break;
                default:
                    break;
            }
        }
    };

    private Handler mTimeFindRunSatus = new Handler() {
        public void handleMessage(android.os.Message msg) {
            mTimeFindRunSatus.removeMessages(1002);
            findTeaMachine();
            if (moutTeaMachineArrys.size() > 0) {
                mTimeFindRunSatus.sendEmptyMessageDelayed(1002, 2000);

            }

        }
    };

    private Handler mTimeTestOne = new Handler() {
        public void handleMessage(android.os.Message msg) {
            mTimeTestOne.removeMessages(1001);
            //  mUserDataThread.start();


        }
    };
    private Handler mTimeInitOne = new Handler() {
        public void handleMessage(android.os.Message msg) {
            mTimeInitOne.removeMessages(2001);
            initMenu();

            Message msga = new Message();
            String str1;
            str1 = "";

            msga.what = CHANGE_START;
            msga.obj = str1;
            mMqttHandler.sendMessage(msga);

            // handlScanInfor("?o=20052682242507090001&equ=yxzbc07");
        }
    };
    private Handler mTimeHandlerOne = new Handler() {
        public void handleMessage(android.os.Message msg) {
            mTimeHandlerOne.removeMessages(100);
            handlCurrentTime();
        }
    };

    //历史记录
    private int mSaleRecordSysncTime = 180000;
    private Handler mSaleRecordSysncHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            mSaleRecordSysncHandler.removeMessages(2);
            handlSalesRecordData();


        }
    };
    private int mClearRecordSysncTime = 180000;
    private Handler mClearRecordSysncHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            mClearRecordSysncHandler.removeMessages(3);


            handlClearRecordData();


        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home_pages);
        myDatabaseInfor = new MyDatabaseInfor(getApplicationContext());
        mBdwrite = myDatabaseInfor.getWritableDatabase();
        mBdread = myDatabaseInfor.getReadableDatabase();

        mContext = this;
        mHomePages = this;
        getSupportActionBar().hide();
        int flag = WindowManager.LayoutParams.FLAG_FULLSCREEN;
        Window myWindow = this.getWindow();
        myWindow.setFlags(flag, flag);
        hideBottomUIMenu();
        initPaths();
        fManager = this.getFragmentManager();

        // 设置key事件最大间隔，默认20ms，部分低端扫码枪效率低
        ScanGun.setMaxKeysInterval(50);
        mScanGun = new ScanGun(new ScanGun.ScanGunCallBack() {

            @Override
            public void onScanFinish(String scanResult) {

                if (scanResult == null || scanResult.length() <= 0) {
                    return;
                }
                Message msg = new Message();
                String str1;
                str1 = scanResult;

                Log.d(TAG, "ScanGun str1str1==" + str1);
                msg.what = CONTENT_DATA_ONE;
                msg.obj = str1;
                mContHandler.sendMessage(msg);


            }
        });
        initData();
        initView();
        if (!mIsVirtual) {
            initSeriel();
        }

        handlCurrentTime();
//        String device_status = Urlinfor.getmUrlinfor().getDeviceStatus();
//        if (Integer.parseInt(device_status) == 2) {
//            String errors = mContext.getResources().getString(R.string.main_local_device_error_two);
//            home_gae_error_rlativeLayout.setVisibility(RelativeLayout.VISIBLE);
//
//            mtxtErrorTip.setText(mContext.getResources().getString(R.string.main_local_device_two) + errors);
//            // mtxtErrorTip.setVisibility(TextView.VISIBLE);
//            // return;
//        }
        //   mTimeTestOne.sendEmptyMessageDelayed(1001, 1000);
        mTimeInitOne.sendEmptyMessageDelayed(2001, 1000);
    //    handlSalesRecordData();
   //     handlClearRecordData();

//        if (mScancodePopupView == null) {
//            mScancodePopupView = new ScancodePopupView(mContext);
//        }
//
//        mScancodePopupView.show();
//        mScancodePopupView.setNameInfor("ceshi");
//        mScancodePopupView.setRunTime("aa");

//        moutTeaMachineArrys.add(1001);
//        handlOutTeaMachine();

        //     handlTeaMachine();

//        if (mTimeHandlerCleanOne != null) {
//            mTimeHandlerCleanOne.sendEmptyMessageDelayed(304, 5 * 60 * 1000); //5 * 60 * 1000
//
//        }
    }

    public void initPaths() {


        //判断SD卡是否存在 getExternalStorageDirectory
        if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
            Log.d(TAG, "onCreate:MediaActivity =1");
            mdirName = Environment.getExternalStorageDirectory().getAbsolutePath()
                    + File.separator + "twbefile" + File.separator;
            File file = new File(mdirName);
            Log.d(TAG, "onCreate:MediaActivity =2=" + mdirName);
            if (!file.exists()) {
                Log.d(TAG, "onCreate:MediaActivity =3");
                file.mkdir();
            }
            mdirFileName  = Environment.getExternalStorageDirectory().getAbsolutePath()
                    + File.separator + "twbetxt" + File.separator;
            File filea = new File(mdirFileName);
            Log.d(TAG, "onCreate:MediaActivity =3=" + mdirFileName);
            if (!filea.exists()) {
                Log.d(TAG, "onCreate:MediaActivity =3");
                filea.mkdir();
            }

            mdirFileTextName = mdirFileName+"cnt.txt";
            Log.d(TAG, "onCreate:MediaActivity =4=" + mdirFileTextName);

        }

        try {
            // 首先保存图片
            File pathsFile = mContext.getDir("users", Context.MODE_PRIVATE);//Environment.getExternalStorageDirectory();//getDataDirectory();// mContext.getDir("users", Context.MODE_PRIVATE);

            File appDir = new File(pathsFile, "temp");
            if (!appDir.exists()) {
                Log.d("aaa", "fileIsExists==1");
                appDir.mkdir();
            } else {
                Log.d("aaa", "fileIsExists==2");
            }
            mSourcePaths = appDir.getAbsolutePath();
            Log.d("aaa", "fileIsExists==3=" + mSourcePaths);
        } catch (Exception e) {
            Log.i("aaa", "崩溃");

        }





    }

    public void initMenu() {
        if (fg1 != null) {
           String infors =ContentInfor.getmUrlinfor().getInforMenusLists();// ContentInfor.getmUrlinfor().getInforMenus();
            // String infors =ContentInfor.getmUrlinfor().getInforMenus();// ContentInfor.getmUrlinfor().getInforMenus();


            fg1.initLeftMenu(infors);
        }

        if (fg2 != null) {
            fg2.clearItem();
            String inforMakes = "";//ContentInfor.getmUrlinfor().getInforMakes();
            String infors ="";// ContentInfor.getmUrlinfor().getInforMenus();
            /*
            try {

                Log.d(TAG, "handlMqttData=inforMakes=" + inforMakes);
                JSONArray infor = new JSONArray(inforMakes);
                JSONArray jsonArrya = new JSONArray(infors);
                for (int m = 0; m < infor.length(); m++) {
                    for (int i = 0; i < jsonArrya.length(); i++) {
                        JSONObject aitema = jsonArrya.getJSONObject(i);
                        String firstMenuid = aitema.opt("firstMenuid").toString();
                        String firstMenuNames = aitema.opt("firstMenuNames").toString();
                        JSONArray secondMenu = aitema.optJSONArray("children");

                        for (int j = 0; j < secondMenu.length(); j++) {
                            JSONObject itema = secondMenu.getJSONObject(j);

                            String secondMenuid = itema.opt("secondMenuid").toString();
                            String secondMenuNames = itema.opt("secondMenuNames").toString();
                            String secondMenuReserve = itema.opt("secondMenuReserve").toString();
                            JSONArray childrenb = itema.optJSONArray("children");
                            for (int k = 0; k < childrenb.length(); k++) {
                                JSONObject atm = childrenb.getJSONObject(k);
                                Log.d(TAG, "handlMqttData: atm==" + atm.toString());
                                Log.d(TAG, "handlMqttData: Urlinfor.getmUrlinfor().getShopInformationNo()==" + Urlinfor.getmUrlinfor().getShopInformationNo());


                                int typeid = atm.optInt("cupTypeid");
                                String typename = atm.optString("cupTypeNames");
                                String errorData = "0";
                                if (atm.has("errorData")) {
                                    errorData = atm.optString("errorData");
                                }
                                String typeinfor = atm.optString("cupTypeReserve");
                                String cupTypeReserve2 = atm.optString("cupTypeReserve2");
                                String productCode = atm.optString("productCode");

                                JSONObject atmb = infor.getJSONObject(m);
                                Log.d(TAG, "handlMqttData: atmb==" + atmb.toString());
                                String orderId = atmb.optString("orderNumbers");
                                String orderTime = atmb.optString("orderTime");
                                String shopCode = atmb.optString("shopCode");
                                String cupNum = atmb.optString("cupNumbers");
                                Log.d(TAG, "handlMqttData: shopCode==" + shopCode);

                                String productCodea = atmb.optString("cupType");
                                Log.d(TAG, "handlMqttData: productCodea=1=" + productCodea);
                                Log.d(TAG, "handlMqttData: productCode=1=" + productCode);

                                if (productCode.length() > 0 && productCodea.length() > 0 && productCode.equals(productCodea) && shopCode.equals(Urlinfor.getmUrlinfor().getShopInformationNo())) {
                                    JSONArray content = atm.optJSONArray("children");
                                    Log.d(TAG, "handlMqttData: productCode==" + productCode);

                                    if (fg2 != null) {

                                        String contentName = cupNum;
                                        String orderNumber = orderId;

                                        String firstName = firstMenuid;
                                        String secondName = secondMenuNames;
                                        String cupType = typename;
                                        String beverageNameTag = cupTypeReserve2;
                                        String orderDetail = content.toString();
                                        String cupTypeids = String.valueOf(typeid);

                                        fg2.addItem(new OrderContentData(contentName,
                                                orderNumber, orderTime, firstName,
                                                secondName, cupType, beverageNameTag,
                                                orderDetail, firstMenuid, secondMenuid,
                                                cupTypeids, secondMenuReserve, "", errorData));


                                    }

                                }


                            }
                        }
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();


            }
            */

//            fg2.addItem(new OrderContentData(imgId, menuId, contentName,
//                    orderNumber, orderTime, firstName,
//                    secondName, cupType, beverageNameTag,
//                    orderDetail, firstMenuid, secondMenuid,
//                    cupTypeids, cupTypeReserve2));


        }

        if (fg3 != null) {
            Log.d(TAG, "initMenu_____");
            Log.d(TAG, "initMenu: pina1==" + mPinsNames.keySet());
            for (int pina : mPinsNames.keySet()) {
                Log.d(TAG, "initMenu: pina==" + pina);
                if(pina >= 1000){
                    continue;
                }
                fg3.addItem(new HandlContentData(pina, mPinsNames.get(pina), "10"));
            }
            fg3.handlLens();

        }
        Log.d(TAG, "initMenu:mpinsUserInfors==" + mpinsUserInfors);
        Log.d(TAG, "initMenu:mPinsSpeeds==" + mPinsSpeeds);


        if (fg4 != null) {
            fg4.initLeftMenu("", mpinsUserInfors, mPinsSpeeds);
        }

        if (DevicesInfors.getDevicesInfors().getDevice_type() == 3) {
            handlDeviceType();
        }

        Message msg = new Message();
        String str1;
        str1 = "";

        msg.what = CHANGE_START;
        msg.obj = str1;
        mMqttHandler.sendMessage(msg);
    }

    public void initSeriel() {

        if (moutTeaMachineArrys != null) {
            moutTeaMachineArrys.clear();
        }

        mSerialPortUtils.setOnDataReceiveListener(new SerialPortUtils.OnDataReceiveListener() {
            @Override
            public void onDataReceive(byte[] buffer, int size) {


                Log.d(TAG, "onDataReceive:aa =" + String.valueOf(size));
                int uart3_lens = 0;
                int errors = 0;
                byte g_temp_check = 0x00;
                byte uart3_types = 0x00;
                if (size > 0) {

                    String h = "";
                    for (int i = 0; i < size; i++) {
                        mBuffStr[m_AllLength + i] = buffer[i];
                        String temp = Integer.toHexString(buffer[i] & 0xFF);
                        if (temp.length() == 1) {
                            temp = "0" + temp;
                        }
                        h = h + temp;

                    }
                    Log.d(TAG, "onDataReceive---aaa: h=" + h);

                    m_AllLength += size;
                    Log.d(TAG, "onDataReceive: m_AllLength=" + String.valueOf(m_AllLength));

                    boolean isEnd = false;
                    for (int i = 0; i < m_AllLength; i++) {
                        if (mBuffStr[i] == 'W' && mBuffStr[i + 1] == 'X' && (i + 9) <= m_AllLength) {
                            uart3_lens = (int) mBuffStr[i + 7];
                            Log.d(TAG, "onDataReceive: uart3_lens=" + Integer.toHexString(uart3_lens));

                            if ((uart3_lens + i + 8) <= m_AllLength) {
                                g_temp_check = 0;

                                for (int j = i; j <= (uart3_lens + i + 7); j++) {

                                    g_temp_check += mBuffStr[j];
                                }
                                Log.d(TAG, "onDataReceive: g_temp_check=" + Integer.toHexString(g_temp_check & 0xFF));
                                byte uart3_type = mBuffStr[i + 6];
                                int frame_id = (int) mBuffStr[i + 3];
                                if (mBuffStr[uart3_lens + i + 8] == g_temp_check) {
                                    Log.d(TAG, "onDataReceive: aa=");

                                    if (m_frame_id == frame_id) {


                                        uart3_types = uart3_type;
                                        if (uart3_types == 0x73) {
                                            //  clearDataError = (int) mBuffStr[i + 8];
                                        }
                                        if (uart3_types == (byte) 0x62) {
                                            // mPinsShortage;
                                            for (int k = 0; k < uart3_lens; k += 2) {
                                                int pnsa = (int) mBuffStr[i + k + 8];
                                                int sta = (int) mBuffStr[i + k + 9];
                                                if (sta == 1) {
                                                    mPinsShortage.add(pnsa);
                                                }
                                            }

                                        }
                                        isEnd = true;
                                    } else {
                                        Log.d(TAG, "onDataReceive: dd=2");
                                        m_AllLength = 0;

                                        mBuffStr = new byte[1024 * 3];
                                    }

                                }
                            }

                        }
                    }


                    if (isEnd) {
                        Log.d(TAG, "onDataReceive: dd=");
                        m_AllLength = 0;

                        mBuffStr = new byte[1024 * 3];
                        if (uart3_types == (byte) 0x62) {
                            if (mIsCancels) {
                                return;
                            }
                            // mPinsShortage;
                            if (mPinsShortage.size() > 0) {
                                mTimeHandlerCmdThree.sendEmptyMessageDelayed(501, 300);
                            }

                        }
                        if (uart3_types == (byte) 0x63) {
                            if (mIsCancels) {
                                return;
                            }
                            mTimeHandlerCmdOne.sendEmptyMessageDelayed(500, 800);
//                            if (isChechs) {
//
//                                mTimeHandlerCmdOne.sendEmptyMessageDelayed(500, 300);
//                                isChechs = false;
//                            } else {
//                                mTimeHandlerTwo.sendEmptyMessageDelayed(101, 300);
//
//
//                            }
                        }
                        if (uart3_types == (byte) 0x71) {
                            mTimeHandlerCmdTwo.sendEmptyMessageDelayed(501, 1000);
                        }

                        uart3_types = 0x00;

                        return;
                    }


                }

            }
        });
        mSerialPort = mSerialPortUtils.openSerialPort();
        if (mSerialPort == null) {

            Toast.makeText(mContext, "串口打开失败1", Toast.LENGTH_SHORT).show();
            return;
        }


        mSerialWeightPort = mSerialPortWeightUtils.openSerialPort();
        mSerialPortWeightUtils.setOnDataReceiveListener(new SerialPortWeightUtils.OnDataReceiveListener() {
            @Override
            public void onDataReceive(byte[] buffer, int size) {
                int uart3_weight = 0;
                int errors = 0;

                //  mBuffStr = new byte[1024 * 3];
                //   private  int m_AllLength=0;
                //   private  int m_currenLengt=0;
                Log.d("aaa", "mSerialPortWeightUtils: h=" + String.valueOf(size));

                if (size > 0) {

                    String h = "";
                    for (int i = 0; i < size; i++) {
                        mBuffWeightStr[m_AllLength + i] = buffer[i];
                        String temp = Integer.toHexString(buffer[i] & 0xFF);
                        if (temp.length() == 1) {
                            temp = "0" + temp;
                        }
                        h = h + temp;

                    }
                    Log.d("aaa", "mSerialPortWeightUtils: h=" + h);

                    m_AllLength += size;
                    Log.d("aaa", "mSerialPortWeightUtils: m_AllLength=" + String.valueOf(m_AllLength));

                    boolean isEnd = false;
                    for (int i = 0; i < m_AllLength; i++) {
                        if (mBuffWeightStr[i] == 0x01 && mBuffWeightStr[i + 1] == 0x03 && (i + 8) <= m_AllLength) {
                            //     uart3_weight = ByteUtils.byteToInt(mBuffWeightStr[i + 5]);
                            //     uart3_weight = (uart3_weight << 8) + ByteUtils.byteToInt(mBuffWeightStr[i + 6]);
                            ByteBuffer buffersa = ByteBuffer.allocate(4);
                            buffersa.put((byte) 0);
                            buffersa.put((byte) 0);


                            buffersa.put((byte) mBuffWeightStr[i + 5]);
                            buffersa.put((byte) mBuffWeightStr[i + 6]);
                            buffersa.rewind();
                            int cmdsa = buffersa.getInt();
                            uart3_weight = cmdsa;
                            Log.d("aaa", "mSerialPortWeightUtils: uart3_lens=" + Integer.toHexString(uart3_weight));


                            isEnd = true;


                        }
                    }

                    //   Toast.makeText(mTempContext,"zhengliang"+String.valueOf(uart3_weight), Toast.LENGTH_SHORT).show();

                    if (isEnd) {
                        Log.d("aaa", "mSerialPortWeightUtils: dd=");
                        Log.d("aaa", "mSerialPortWeightUtils: uart3_weight=" + String.valueOf(uart3_weight));
                        m_AllLength = 0;

                        mBuffWeightStr = new byte[1024 * 3];
                        Log.d(TAG, "mSerialPortWeightUtils: mSerialPortWeightUtils =1s=mEmptyType=" + mEmptyType);
                        if (mIsCancels) {
                            Log.d(TAG, "mSerialPortWeightUtils: mSerialPortWeightUtils =1s=mIsCancels=" + mIsCancels);

                            return;
                        }
                        if (mCurrentTypes == 3 || mCurrentTypes == 4) {
                            Log.d(TAG, "mSerialPortWeightUtils: mSerialPortWeightUtils =1=mEmptyType=" + mEmptyType);

                            mCurrentAllWeighs = uart3_weight;
                            Log.d(TAG, "mSerialPortWeightUtils: mSerialPortWeightUtils =2=mEmptyType=" + mEmptyType);
                            mTimeHandlerWeighTwo.sendEmptyMessageDelayed(301, 30);
                            return;
                        }

                        if (mCurrentTypes == 1 && moutmaterialsArrys.size() > 0) {
                            Log.d(TAG, "mSerialPortWeightUtils: mCurrentTypes=" + mCurrentTypes);
                            Log.d(TAG, "mSerialPortWeightUtils: moutmaterialsArrys.size()=" + moutmaterialsArrys.size());

                            mCurrentAllWeighs = uart3_weight;
                            mTimeHandlerWeighThree.sendEmptyMessageDelayed(302, 30);
                            return;
                        }
                        if (mCurrentTypes == 1 && mCheckWeighStatus) {
                            Log.d(TAG, "mSerialPortWeightUtils: mCurrentTypes=" + mCurrentTypes);
                            Log.d(TAG, "mSerialPortWeightUtils: mCheckWeighStatus=" + mCheckWeighStatus);

                            mCurrentAllWeighs = uart3_weight;
                            mTimeHandlerWeighThree.sendEmptyMessageDelayed(302, 30);
                            return;
                        }
                        if (mCurrentRunStatus == 0) {
                            mCurrentRunStatus = 1;
                            mInitWeight = uart3_weight;
                            Log.d(TAG, "mSerialPortWeightUtils: mSerialPortWeightUtils =1s=mCurrentRunStatus1=" + mCurrentRunStatus);

                            Log.d(TAG, "mSerialPortWeightUtils: mSerialPortWeightUtils =1s=mInitWeight=" + mInitWeight);

                        } else {
                            Log.d(TAG, "mSerialPortWeightUtils: mSerialPortWeightUtils =1s=mCurrentRunStatus=" + mCurrentRunStatus);

                            if (mCurrentRunStatus == 2) {
                                mCurrentRunStatus = 3;
                                mEndWeight = uart3_weight;
                            }
                            Log.d(TAG, "mSerialPortWeightUtils: mSerialPortWeightUtils =1s=mEndWeight=" + mEndWeight);

                        }


                        return;
                    }

                    Log.d("aaa", "mSerialPortWeightUtils: m_currenLengt=" + String.valueOf(m_currenLengt));


                }

            }
        });

        mSerialScanPort = mSerialPortScanUtils.openSerialPort();
        mSerialPortScanUtils.setOnDataReceiveListener(new SerialPortScanUtils.OnDataReceiveListener() {
            @Override
            public void onDataReceive(byte[] buffer, int size) {
                Log.d("aaa", "mSerialPortWeightUtils: h=" + String.valueOf(size));

                if (size > 0) {

                    String h = "";
                    for (int i = 0; i < size; i++) {
                        mBuffScanStr[m_AllScanLength + i] = buffer[i];
                        String temp = Integer.toHexString(buffer[i] & 0xFF);
                        if (temp.length() == 1) {
                            temp = "0" + temp;
                        }
                        h = h + temp;

                    }
                    Log.d("aaa", "mSerialPortWeightUtils: h=" + h);

                    m_AllScanLength += size;
                    Log.d("aaa", "mSerialPortWeightUtils: m_AllScanLength=" + String.valueOf(m_AllScanLength));

                    String infors = "";
                    boolean isEnd = false;
                    for (int i = 0; i < m_AllScanLength - 1; i++) {
                        if (mBuffScanStr[i] == 0x0D && mBuffScanStr[i + 1] == 0x0A) {

                            int start = 0; // 截取的起始位置
                            int end = i; // 截取的结束位置
                            int length = end - start;// + 1;
                            byte[] targets = new byte[length];
                            System.arraycopy(mBuffScanStr, start, targets, 0, length);


                            try {
                                String strsa = new String(targets, "UTF-8");
                                infors = strsa;
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                            isEnd = true;
                            break;
                        }
                    }
                    if (isEnd) {
                        Log.d(TAG, "onDataReceive:infors==" + infors);
                        m_AllScanLength = 0;

                        mBuffScanStr = new byte[1024 * 3];
                        Message msg = new Message();
                        String str1;
                        str1 = infors;

                        Log.d(TAG, "ScanGun str1str1==" + str1);
                        msg.what = CONTENT_DATA_ONE;
                        msg.obj = str1;
                        mContHandler.sendMessage(msg);

                        return;
                    }

                }
            }
        });


//        mSerialPortTeaMachineUtils = new SerialPortTeaMachineUtils();
//        private SerialPort mSerialPortTeaMachinePort = null;
//        private byte[] mBuffTeaMachineStr = new byte[1024 * 3];
//        private int m_curTeaMachineLength = 0;
        mSerialPortTeaMachinePort = mSerialPortTeaMachineUtils.openSerialPort();
        mSerialPortTeaMachineUtils.setOnDataReceiveListener(new SerialPortTeaMachineUtils.OnDataReceiveListener() {
            @Override
            public void onDataReceive(byte[] buffer, int size) {
                Log.d("aaa", "mSerialPortTeaMachineUtils: h=" + String.valueOf(size));
                if (size > 0) {

                    String h = "";
                    for (int i = 0; i < size; i++) {
                        mBuffTeaMachineStr[m_curTeaMachineLength + i] = buffer[i];
                        String temp = Integer.toHexString(buffer[i] & 0xFF);
                        if (temp.length() == 1) {
                            temp = "0" + temp;
                        }
                        h = h + temp;

                    }
                    Log.d("aaa", "mSerialPortTeaMachineUtils: h=" + h);

                    m_curTeaMachineLength += size;
                    Log.d("aaa", "mSerialPortTeaMachineUtils: m_curTeaMachineLength=" + String.valueOf(m_curTeaMachineLength));
                    boolean has0x01 = containsByte(mBuffTeaMachineStr, (byte) 0x01); // true
                    boolean has0x04 = containsByte(mBuffTeaMachineStr, (byte) 0x04); // true

                    String infors = "";

                    if (has0x01 && has0x04) {
                        Log.d(TAG, "mSerialPortTeaMachineUtils:infors==" + infors);
//                        h = "";
//                        for (int i = 0; i < size; i++) {
//                            mBuffTeaMachineStr[ i] = buffer[i];
//                            String temp = Integer.toHexString(buffer[i] & 0xFF);
//                            if (temp.length() == 1) {
//                                temp = "0" + temp;
//                            }
//                            h = h + temp;
//
//                        }
//                        Log.d("aaa", "mSerialPortTeaMachineUtils: hb=" + h);

                        byte[] arryb = handlTransformation(mBuffTeaMachineStr);
//                        String ha = "";
//                        for (int i = 0; i < arryb.length; i++) {
//
//                            String temp = Integer.toHexString(arryb[i] & 0xFF);
//                            if (temp.length() == 1) {
//                                temp = "0" + temp;
//                            }
//                            ha =ha + temp;
//
//                        }
//                        Log.d("aaa", "mSerialPortTeaMachineUtils: ha=" + ha);

                        if (arryb[1] == 0x68) {
                            byte cnta = (byte) (arryb[11] & 0xF0);

                            if (cnta == 0x00) {
                                byte cntb = (byte) (arryb[11] & 0x0F);
                                Integer temPina = 0;
                                if (moutTeaMachineArrys.size() > 0) {
                                    temPina = moutTeaMachineArrys.get(0);
                                }

                                if (cntb == 0x02) {

                                    if (temPina >= 1000 && temPina < 2000) {
                                        misSend =false;
                                        Message msg = new Message();
                                        String str1;
                                        str1 = infors;

                                        Log.d(TAG, "mSerialPortTeaMachineUtils str1str1==" + str1);
                                        msg.what = CONTENT_DATA_TWO;
                                        msg.obj = str1;
                                        mContHandler.sendMessage(msg);
                                        m_curTeaMachineLength = 0;

                                        mBuffTeaMachineStr = new byte[1024 * 3];

                                        return;
                                    } else {
                                        misSend =false;
                                        Message msg = new Message();
                                        String str1;
                                        str1 = infors;

                                        Log.d(TAG, "mSerialPortTeaMachineUtils str1str1==" + str1);
                                        msg.what = CONTENT_DATA_THREE;
                                        msg.obj = str1;
                                        mContHandler.sendMessage(msg);
                                        m_curTeaMachineLength = 0;

                                        mBuffTeaMachineStr = new byte[1024 * 3];

                                        return;
                                    }
                                } else {
                                    if (cntb == 0x03) {

                                        if (temPina >= 2000 && temPina < 3000) {
                                            misSend =false;
                                            Message msg = new Message();
                                            String str1;
                                            str1 = infors;

                                            Log.d(TAG, "mSerialPortTeaMachineUtils str1str1==" + str1);
                                            msg.what = CONTENT_DATA_TWO;
                                            msg.obj = str1;
                                            mContHandler.sendMessage(msg);
                                            m_curTeaMachineLength = 0;

                                            mBuffTeaMachineStr = new byte[1024 * 3];

                                            return;
                                        } else {
                                            misSend =false;
                                            Message msg = new Message();
                                            String str1;
                                            str1 = infors;

                                            Log.d(TAG, "mSerialPortTeaMachineUtils str1str1==" + str1);
                                            msg.what = CONTENT_DATA_FOUR;
                                            msg.obj = str1;
                                            mContHandler.sendMessage(msg);
                                            m_curTeaMachineLength = 0;

                                            mBuffTeaMachineStr = new byte[1024 * 3];

                                            return;
                                        }
                                    } else {


                                        if (cntb == 0x01) {
                                            misSend =false;
                                            Message msg = new Message();
                                            String str1;
                                            str1 = infors;

                                            Log.d(TAG, "mSerialPortTeaMachineUtils str1str1==" + str1);
                                            msg.what = CONTENT_DATA_TWO;
                                            msg.obj = str1;
                                            mContHandler.sendMessage(msg);
                                            m_curTeaMachineLength = 0;

                                            mBuffTeaMachineStr = new byte[1024 * 3];

                                            return;
                                        } else {
                                            misSend =false;
                                            Message msg = new Message();
                                            String str1;
                                            str1 = infors;

                                            Log.d(TAG, "mSerialPortTeaMachineUtils str1str1==" + str1);
                                            msg.what = CONTENT_DATA_FIVE;
                                            msg.obj = str1;
                                            mContHandler.sendMessage(msg);
                                            m_curTeaMachineLength = 0;

                                            mBuffTeaMachineStr = new byte[1024 * 3];

                                            return;
                                        }

                                    }


                                }

                            }
                        }

                        m_curTeaMachineLength = 0;

                        mBuffTeaMachineStr = new byte[1024 * 3];


                        return;
                    }
                }
            }
        });


    }

    private void initData() {

        if(mPinsMerilData != null){
            mPinsMerilData.clear();
        }

        if(materialsPins != null){
            materialsPins.clear();
        }

        try {

            JSONArray arry1 = new JSONArray(ContentInfor.getmUrlinfor().getInforAllMaterial());
            for (int j = 0; j < arry1.length(); j++) {
                JSONObject itema = arry1.getJSONObject(j);



                String name = itema.opt("name").toString();
                int max = 999999;

                if (!itema.isNull("max")) {
                    max = itema.optInt("max");
                }

                int min = 0;

                if (!itema.isNull("min")) {
                    min = itema.optInt("min");
                }

                String materialName = "";

                if (!itema.isNull("materialName")) {
                    materialName = itema.optString("materialName");
                }

                String materialTypeName = "";

                if (!itema.isNull("materialTypeName")) {
                    materialTypeName = itema.optString("materialTypeName");
                }
                materialsCapacity.put(name, max);
                int id = 0;

                if (!itema.isNull("id")) {
                    id = itema.optInt("id");
                }
                materialsNumsCapacity.put(id, max);
            }

            JSONArray arrysa = new JSONArray(ContentInfor.getmUrlinfor().getInforMaterial());

         //   materialsPins.put(23551 ,9 );
            for (int j = 0; j < arrysa.length(); j++) {
                JSONObject itema = arrysa.getJSONObject(j);
                int channelNumber = 0;

                if (itema.isNull("channelNumber")) {
                    continue;

                }
                channelNumber = itema.optInt("channelNumber");
                int materiaId = 0;

                if (!itema.isNull("materiaId")) {
                    materiaId = itema.optInt("materiaId");
                }
                materialsPins.put(materiaId ,channelNumber );
                String materialName = "";

                if (!itema.isNull("materiaName")) {
                    materialName = itema.optString("materiaName");
                }

                String materialTypeName = "";

                if (!itema.isNull("materialTypeName")) {
                    materialTypeName = itema.optString("materialTypeName");
                }

                Log.d(TAG, "devicematerial===materialName=a=: " + materialName);
                Log.d(TAG, "devicematerial===itema=a=: " + itema.toString());


                String materialpins = String.valueOf(channelNumber);
                String materialReserve1 = materialName;
                String materialReserve2 = "20";
                String materialId = String.valueOf(materiaId);
                String materialPins = materialpins;
                int max = 999999;

                if (materialsNumsCapacity.keySet().contains(materialId)) {
                    max = materialsNumsCapacity.get(materialId);
                }
                String materialFull = String.valueOf(max);
                String compensate = "0";
                String materialRemind = "10";
                String materialDrit = "1";
                String materialCricle = "1";
                String materialCriName = "3";//档位
                if (!materialDrit.contains("1")) {
                    materialDrit = "0";
                } else {
                    materialDrit = "1";

                }
                if (itema.has("compensate")) {
                    compensate = itema.opt("compensate").toString();
                }
                String rack_type = "0"; //上料 2是打开克重
                if (itema.has("rack_type")) {
                    rack_type = itema.opt("rack_type").toString();
                }
                String empty_type = "0";//排空 2是打开克重
                if (itema.has("empty_type")) {
                    empty_type = itema.opt("empty_type").toString();
                }
                String compensate_empty = "0";// 一键排空(g) 补偿克重(g)
                if (itema.has("compensate_empty")) {
                    compensate_empty = itema.opt("compensate_empty").toString();
                }
                String compensate_rack = "0";// 一键上料(g) 补偿克重(g)
                if (itema.has("compensate_rack")) {
                    compensate_rack = itema.opt("compensate_rack").toString();
                }
                String rack_2 = "0";//一键上料(g)
                if (itema.has("rack_2")) {
                    rack_2 = itema.opt("rack_2").toString();
                }
                String empty_2 = "0";//一键排空(g)
                if (itema.has("empty_2")) {
                    empty_2 = itema.opt("empty_2").toString();
                }
                String weighing_verification = "0";//称重校验效期(秒)
                if (itema.has("weighing_verification")) {
                    weighing_verification = itema.opt("weighing_verification").toString();
                }

                Log.d(TAG, "devicematerial-=--materialDrit=a=: " + materialDrit);
                Log.d(TAG, "devicematerial-=--materialPins=a=: " + materialPins);
                Log.d(TAG, "devicematerial-=--materialFull=a=: " + materialFull);

                updatePinPeriod(Integer.parseInt(materialpins));
                mPinsNames.put(Integer.parseInt(materialpins), materialReserve1);
                //MerilData(String materialId, String materialPins, String materialName, String materialFull, String materialRemind, String materialDrit, String materialCricle, String materialCriName, String materialPerids, String compensate, String rack_type, String empty_type, String compensate_empty, String compensate_rack, String rack_2, String empty_2)

                //   MerilData merilData = new MerilData(materialId, materialPins, materialName, materialFull, materialRemind, materialDrit, materialCricle, materialCriName, materialReserve2, compensate);

                MerilData merilData = new MerilData(materialId, materialPins, materialName, materialFull, materialRemind, materialDrit, materialCricle, materialCriName, materialReserve2, compensate, rack_type, empty_type, compensate_empty, compensate_rack, rack_2, empty_2, weighing_verification);
                mPinsMerilData.put(Integer.parseInt(materialpins), merilData);
            }
            Log.d(TAG, "devicematerial===mPinsNames=a=: " + mPinsNames);
            Log.d(TAG, "devicematerial===materialsPins=a=: " + materialsPins.toString() );

            /*
            JSONObject objcta = new JSONObject(ContentInfor.getmUrlinfor().getInforMaterial());
            JSONArray devicematerial = objcta.optJSONArray("rows");
            Log.d(TAG, "initData: devicematerial==" + devicematerial.toString());
            for (int j = 0; j < devicematerial.length(); j++) {
                JSONObject itema = devicematerial.getJSONObject(j);
                Log.d(TAG, "devicematerial--itema: " + itema);
                String materialpins = itema.opt("materialpins").toString();
                String materialReserve1 = itema.opt("materialReserve1").toString();
                String materialReserve2 = itema.opt("materialReserve2").toString();
                String materialId = itema.opt("materialid").toString();
                String materialPins = materialpins;
                String materialName = materialReserve1;
                String materialFull = itema.opt("materialFull").toString();
                String compensate = "0";

                String materialRemind = itema.opt("materialRemind").toString();
                String materialDrit = itema.opt("materialReserve4").toString();
                String materialCricle = itema.opt("materialReserve6").toString();
                String materialCriName = itema.opt("materialReserve5").toString();//档位
                Log.d(TAG, "devicematerial materialpins: " + materialpins);
                Log.d(TAG, "devicematerial materialDrit: " + materialDrit);
                Log.d(TAG, "devicematerial materialCricle: " + materialCricle);
                Log.d(TAG, "devicematerial materialCriName: " + materialCriName);
                if (!materialDrit.contains("1")) {
                    materialDrit = "0";
                } else {
                    materialDrit = "1";

                }
                if (itema.has("compensate")) {
                    compensate = itema.opt("compensate").toString();
                }
                String rack_type = "0"; //上料 2是打开克重
                if (itema.has("rack_type")) {
                    rack_type = itema.opt("rack_type").toString();
                }
                String empty_type = "0";//排空 2是打开克重
                if (itema.has("empty_type")) {
                    empty_type = itema.opt("empty_type").toString();
                }
                String compensate_empty = "0";// 一键排空(g) 补偿克重(g)
                if (itema.has("compensate_empty")) {
                    compensate_empty = itema.opt("compensate_empty").toString();
                }
                String compensate_rack = "0";// 一键上料(g) 补偿克重(g)
                if (itema.has("compensate_rack")) {
                    compensate_rack = itema.opt("compensate_rack").toString();
                }
                String rack_2 = "0";//一键上料(g)
                if (itema.has("rack_2")) {
                    rack_2 = itema.opt("rack_2").toString();
                }
                String empty_2 = "0";//一键排空(g)
                if (itema.has("empty_2")) {
                    empty_2 = itema.opt("empty_2").toString();
                }
                String weighing_verification = "0";//称重校验效期(秒)
                if (itema.has("weighing_verification")) {
                    weighing_verification = itema.opt("weighing_verification").toString();
                }

                Log.d(TAG, "devicematerial materialDrit=a=: " + materialDrit);

                updatePinPeriod(Integer.parseInt(materialpins));
                mPinsNames.put(Integer.parseInt(materialpins), materialReserve1);
                //MerilData(String materialId, String materialPins, String materialName, String materialFull, String materialRemind, String materialDrit, String materialCricle, String materialCriName, String materialPerids, String compensate, String rack_type, String empty_type, String compensate_empty, String compensate_rack, String rack_2, String empty_2)

                //   MerilData merilData = new MerilData(materialId, materialPins, materialName, materialFull, materialRemind, materialDrit, materialCricle, materialCriName, materialReserve2, compensate);

                MerilData merilData = new MerilData(materialId, materialPins, materialName, materialFull, materialRemind, materialDrit, materialCricle, materialCriName, materialReserve2, compensate, rack_type, empty_type, compensate_empty, compensate_rack, rack_2, empty_2, weighing_verification);
                mPinsMerilData.put(Integer.parseInt(materialpins), merilData);
            }
            */
        } catch (JSONException e) {
            e.printStackTrace();

        }

    }

    private void initView() {
        homepages_background_layout_linearlayout_one = findViewById(R.id.homepages_background_layout_linearlayout_one);
        home_page_top_relativelayout= findViewById(R.id.home_page_top_relativelayout);
        home_page_top_imageview= findViewById(R.id.home_page_top_imageview);


        homepages_background_layout_linearlayout_two = findViewById(R.id.homepages_background_layout_linearlayout_two);
        homepages_background_layout_linearlayout_three = findViewById(R.id.homepages_background_layout_linearlayout_three);
        mCustomVideoView = findViewById(R.id.media_video_view);
        mCustomVideoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mPlayer) {
                handlPlayPath();
            }
        });


        main_model_change_btn = findViewById(R.id.main_model_change_btn);

        main_model_change_btn.setAlpha((float) 0.0);

        main_model_change_btn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if (!device_model_status) {

                    if (mPasswrdSetdialog == null) {
                        mPasswrdSetdialog = new PasswrdSetdialog(mContext);
                    }


                    mPasswrdSetdialog.show();
                    mPasswrdSetdialog.setCancel(true, mContext.getResources().getString(R.string.passwrd_set_title_infor_s));
                    mPasswrdSetdialog.setPopupTipInfor("");
                    mPasswrdSetdialog.setBtnOnClick(new View.OnClickListener() {
                        public void onClick(View v) {

                            String infors = mPasswrdSetdialog.getPopupTipInfor();
                            Log.d("aaa", "aaa infors=" + infors);
                            mPasswrdSetdialog.dismiss();

                            if (infors.equals(ConfigParams.getConfigParams().getPwds())) {
                                device_model_status = !device_model_status;
                                if (device_model_status) {
                                    main_model_change_btn.setText(R.string.main_model_change_one);
                                    if (homepages_background_layout_linearlayout_one != null) {
                                        homepages_background_layout_linearlayout_one.setVisibility(RelativeLayout.VISIBLE);
                                    }
                                    if (home_page_top_relativelayout != null) {
                                        home_page_top_relativelayout.setVisibility(RelativeLayout.VISIBLE);
                                    }
                                    if (home_page_top_imageview != null) {
                                        home_page_top_imageview.setVisibility(RelativeLayout.VISIBLE);
                                    }


                                    if (homepages_background_layout_linearlayout_two != null) {
                                        homepages_background_layout_linearlayout_two.setVisibility(RelativeLayout.VISIBLE);
                                    }
                                    if (homepages_background_layout_linearlayout_three != null) {
                                        homepages_background_layout_linearlayout_three.setVisibility(RelativeLayout.GONE);
                                    }

                                } else {
                                    main_model_change_btn.setText(R.string.main_model_change_two);
                                    if (homepages_background_layout_linearlayout_one != null) {
                                        homepages_background_layout_linearlayout_one.setVisibility(RelativeLayout.GONE);
                                    }
                                    if (home_page_top_relativelayout != null) {
                                        home_page_top_relativelayout.setVisibility(RelativeLayout.GONE);
                                    }
                                    if (home_page_top_imageview != null) {
                                        home_page_top_imageview.setVisibility(RelativeLayout.GONE);
                                    }

                                    if (homepages_background_layout_linearlayout_two != null) {
                                        homepages_background_layout_linearlayout_two.setVisibility(RelativeLayout.GONE);
                                    }
                                    if (homepages_background_layout_linearlayout_three != null) {
                                        homepages_background_layout_linearlayout_three.setVisibility(RelativeLayout.VISIBLE);
                                    }

                                }

                            } else {
                                Toast.makeText(mContext, mContext.getResources().getString(R.string.password_text_center_input_error_tip), Toast.LENGTH_SHORT).show();

                            }

                        }
                    });


                } else {
                    device_model_status = !device_model_status;
                    if (device_model_status) {
                        main_model_change_btn.setText(R.string.main_model_change_one);
                        if (homepages_background_layout_linearlayout_one != null) {
                            homepages_background_layout_linearlayout_one.setVisibility(RelativeLayout.VISIBLE);
                        }
                        if (home_page_top_relativelayout != null) {
                            home_page_top_relativelayout.setVisibility(RelativeLayout.VISIBLE);
                        }
                        if (home_page_top_imageview != null) {
                            home_page_top_imageview.setVisibility(RelativeLayout.VISIBLE);
                        }

                        if (homepages_background_layout_linearlayout_two != null) {
                            homepages_background_layout_linearlayout_two.setVisibility(RelativeLayout.VISIBLE);
                        }
                        if (homepages_background_layout_linearlayout_three != null) {
                            homepages_background_layout_linearlayout_three.setVisibility(RelativeLayout.GONE);
                        }

                    } else {
                        main_model_change_btn.setText(R.string.main_model_change_two);
                        if (homepages_background_layout_linearlayout_one != null) {
                            homepages_background_layout_linearlayout_one.setVisibility(RelativeLayout.GONE);
                        }
                        if (home_page_top_relativelayout != null) {
                            home_page_top_relativelayout.setVisibility(RelativeLayout.GONE);
                        }
                        if (home_page_top_imageview != null) {
                            home_page_top_imageview.setVisibility(RelativeLayout.GONE);
                        }

                        if (homepages_background_layout_linearlayout_two != null) {
                            homepages_background_layout_linearlayout_two.setVisibility(RelativeLayout.GONE);
                        }
                        if (homepages_background_layout_linearlayout_three != null) {
                            homepages_background_layout_linearlayout_three.setVisibility(RelativeLayout.VISIBLE);
                        }

                    }

                }


            }
        });


        top_logo_image_load = (ImageloadView) findViewById(R.id.top_logo_image_load);
        mtxtVersionTip = (TextView) findViewById(R.id.txt_version_tips);
        mtxtErrorTip = (TextView) findViewById(R.id.txt_error_tips);

        home_gae_error_rlativeLayout = findViewById(R.id.home_gae_error_rlativeLayout);
        mtxtVersionTip.setText(mContext.getResources().getString(R.string.main_local_device_one) + Urlinfor.getmUrlinfor().getMdevicenums());


        home_page_switch_button = findViewById(R.id.home_page_switch_button);

        home_page_switch_button.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                isHandleKey = isChecked;
                if (isChecked) {
                    //     homepage_scan_btn.setVisibility(ImageButton.GONE);
                } else {
                    //    homepage_scan_btn.setVisibility(ImageButton.VISIBLE);
                }
            }
        });
        home_page_switch_button.setChecked(isHandleKey);
        home_page_time_text = findViewById(R.id.home_page_time_text);

        home_page_time_btn = findViewById(R.id.home_page_time_btn);
        home_page_time_btn.setAlpha((float) 0);
        home_page_time_btn.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:

                        // 手指按下
                        Log.d("TouchEvent", "ACTION_DOWN");
                        break;
                    case MotionEvent.ACTION_MOVE:
                        // 手指移动
                        Log.d("TouchEvent", "ACTION_MOVE");
                        break;
                    case MotionEvent.ACTION_UP:
                        lastClickTime++;
                        mTimeHandlerClickTime.removeMessages(1001);
                        mTimeHandlerClickTime.sendEmptyMessageDelayed(1001, 1000);


                        // 手指抬起
                        Log.d("TouchEvent", "ACTION_UP=");
                        break;
                    case MotionEvent.ACTION_CANCEL:
                        // 事件被取消
                        Log.d("TouchEvent", "ACTION_CANCEL");
                        break;
                }
                return false;
            }
        });
        /*
        home_page_time_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 处理按钮点击事件
                // Toast.makeText(HomePages.this, "按钮被点击了", Toast.LENGTH_SHORT).show();
               // long clickTime = System.currentTimeMillis();
                Log.d(TAG, "onClick: ==1="+lastClickTime);
                lastClickTime ++;
//                if(lastClickTime > 2){
//                    fullyRestartApp(mContext);
//                }
            //    mTimeHandlerClickTime.removeMessages(1001);
          //     mTimeHandlerClickTime.sendEmptyMessageDelayed(1001, 2000);
//                if (clickTime - lastClickTime < DOUBLE_CLICK_TIME_DELTA) {
//                    // 双击事件
//                    Log.d(TAG, "onClick: ==2");
//                    // fullyRestartApp(mContext);
//                }
//                lastClickTime = clickTime;
            }
        });
        */
//        home_page_time_btn.setOnClickListener(new View.OnClickListener() {
//            public void onClick(View v) {
//
//                long clickTime = System.currentTimeMillis();
//                Log.d(TAG, "onClick: ==1");
////                if (clickTime - lastClickTime < DOUBLE_CLICK_TIME_DELTA) {
////                    // 双击事件
////                    Log.d(TAG, "onClick: ==2");
////                    // fullyRestartApp(mContext);
////                }
////                lastClickTime = clickTime;
//            }
//        });


        homepages_martirel_layout_text_progress = findViewById(R.id.homepages_martirel_layout_text_progress);

        int rows = 1;
        mHomepageMertrielProgressAdapter = new HomepageMertrielProgressAdapter(this, mHomepageMertrielProgressItemData);

        homepages_martirel_layout_text_progress.setAdapter(mHomepageMertrielProgressAdapter);

        mpinsUserInfors.put(-1, 0);

        Cursor cursor = null;
        Set<Integer> merilDatas = mPinsMerilData.keySet();
        cursor = mBdread.rawQuery("select * from capacitytb ", null);
        if (cursor != null && cursor.getCount() > 0) {
            while (cursor.moveToNext()) {

                int pin = cursor.getInt(cursor.getColumnIndex("pin"));
                int surplus = cursor.getInt(cursor.getColumnIndex("surplus"));
                int capacity = cursor.getInt(cursor.getColumnIndex("capacity"));


                if (!merilDatas.contains(pin)) {
                    continue;
                }
                Log.d(TAG, "initData---pin: " + pin);
                Log.d(TAG, "initData---capacity: " + capacity);
                Log.d(TAG, "initData---surplus: " + surplus);
                String namea = "";
                String names = mPinsNames.get(pin);
                if (names != null) {
                    namea = names;
                }
                if( pin < 1000){
                    mHomepageMertrielProgressItemData.add(new HomepageMertrielProgressItemData(pin, namea, capacity, surplus));

                }

                mpinsUserInfors.put(pin, surplus);


            }

        }
        Cursor cursoar = null;

        cursoar = mBdread.rawQuery("select * from speedcheacktb ", null);
        if (cursoar != null && cursoar.getCount() > 0) {
            while (cursoar.moveToNext()) {

                int pin = cursoar.getInt(cursoar.getColumnIndex("pin"));
                float speed = cursoar.getFloat(cursoar.getColumnIndex("speed"));
                float time = cursoar.getFloat(cursoar.getColumnIndex("time"));

                Log.d(TAG, "initData pin: " + pin);

                mPinsSpeeds.put(pin, speed);


            }

        }
        Cursor cursoab = null;

        cursoab = mBdread.rawQuery("select * from pininfor ", null);
        if (cursoab != null && cursoab.getCount() > 0) {
            while (cursoab.moveToNext()) {

                int pin = cursoab.getInt(cursoab.getColumnIndex("pin"));
                int reala = cursoab.getInt(cursoab.getColumnIndex("reala"));

                Log.d(TAG, "initData pin: " + pin);

                mPinsReala.put(pin, reala);


            }

        }


        int nums = mHomepageMertrielProgressItemData.size();
        int numa = nums % 12;
        rows = nums / 12;
        if (numa > 0) {
            rows += 1;
        }
        for (int i = numa; i < 12; i++) {
            mHomepageMertrielProgressItemData.add(new HomepageMertrielProgressItemData(-1, "", 0, 0));

        }
        ViewGroup.LayoutParams layoutParams = homepages_martirel_layout_text_progress.getLayoutParams();// new LinearLayout.LayoutParams((int) mContext.getResources().getDimension(R.dimen.home_material_text_with), (int) mContext.getResources().getDimension(R.dimen.home_material_text_height));

        layoutParams.height = rows * (int) mContext.getResources().getDimension(R.dimen.homepage_top_item_height_size);
        Log.d(TAG, "layoutParams.height ==" + String.valueOf(layoutParams.height));
        homepages_martirel_layout_text_progress.setLayoutParams(layoutParams);

        homepage_nav_top_goods_radiobtn = findViewById(R.id.homepage_nav_top_goods_radiobtn);
        homepage_nav_top_order_radiobtn = findViewById(R.id.homepage_nav_top_order_radiobtn);
        homepage_nav_top_handl_out_radiobtn = findViewById(R.id.homepage_nav_top_handl_out_radiobtn);
        homepage_nav_top_set_radiobtn = findViewById(R.id.homepage_nav_top_set_radiobtn);

        if (DevicesInfors.getDevicesInfors().getDevice_type() == 2) {
            homepage_nav_top_order_radiobtn.setVisibility(RadioButton.GONE);
        }
        if (DevicesInfors.getDevicesInfors().getDevice_type() == 3) {
            homepage_nav_top_goods_radiobtn.setVisibility(RadioButton.GONE);
            homepage_nav_top_order_radiobtn.setChecked(true);
        }
        homepage_nav_top_radioGroup = findViewById(R.id.homepage_nav_top_radioGroup);
        homepage_nav_top_radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (m_select_current_runs == 1) {
                    m_select_current_runs = 0;
                    return;
                }
                if (DevicesInfors.getDevicesInfors().getDevice_type() == 2 || DevicesInfors.getDevicesInfors().getDevice_type() == 3) {
                    switch (checkedId) {
                        case R.id.homepage_nav_top_handl_out_radiobtn:
                        case R.id.homepage_nav_top_set_radiobtn: {
                            m_select_types = checkedId;
                            if (mLoginViews == null) {
                                mLoginViews = new LoginViews(mContext);
                            }
                            mLoginViews.show();
                            mLoginViews.setBtnOnClick(new View.OnClickListener() {
                                public void onClick(View v) {
                                    String username = "";
                                    String userPwd = "";
                                    if (mLoginViews != null) {
                                        username = mLoginViews.getUserName();
                                    }
                                    if (mLoginViews != null) {
                                        userPwd = mLoginViews.getUserPwd();
                                    }
                                    mLoginViews.dismiss();
                                    m_userNames = username;

                                    m_userPwds = getMD5(userPwd);
                                    Log.d("aaa", "onClick:===username=" + username);
                                    Log.d("aaa", "onClick:===userPwd=" + userPwd);
                                    Log.d("aaa", "onClick:===m_userPwds=" + m_userPwds);
                                    mWeiboDialog = WeiboDialogUtils.createLoadingDialog(HomePages.this, mContext.getResources().getString(R.string.loading_text));
                                    sendRequestInitDeviceLogins();
                                }

                            });
                            return;
                        }


                        default:
                            break;
                    }

                }


                FragmentTransaction fTransaction = fManager.beginTransaction();
                hideAllFragment(fTransaction);
                handlRadio();
                switch (checkedId) {
                    case R.id.homepage_nav_top_goods_radiobtn:
                        if (homepage_nav_top_goods_radiobtn != null) {
                            homepage_nav_top_goods_radiobtn.setTextSize(mContext.getResources().getDimension(R.dimen.nav_menu_select));
                            homepage_nav_top_goods_radiobtn.setTypeface(null, Typeface.BOLD);
                        }

                        fTransaction.show(fg1);

                        break;
                    case R.id.homepage_nav_top_order_radiobtn:
                        if (homepage_nav_top_order_radiobtn != null) {
                            homepage_nav_top_order_radiobtn.setTextSize(mContext.getResources().getDimension(R.dimen.nav_menu_select));
                            homepage_nav_top_order_radiobtn.setTypeface(null, Typeface.BOLD);
                        }

                        fTransaction.show(fg2);

                        break;
                    case R.id.homepage_nav_top_handl_out_radiobtn:

                        if (homepage_nav_top_handl_out_radiobtn != null) {
                            homepage_nav_top_handl_out_radiobtn.setTextSize(mContext.getResources().getDimension(R.dimen.nav_menu_select));
                            homepage_nav_top_handl_out_radiobtn.setTypeface(null, Typeface.BOLD);
                        }

                        fTransaction.show(fg3);

                        break;
                    case R.id.homepage_nav_top_set_radiobtn:
                        if (homepage_nav_top_set_radiobtn != null) {
                            homepage_nav_top_set_radiobtn.setTextSize(mContext.getResources().getDimension(R.dimen.nav_menu_select));
                            homepage_nav_top_set_radiobtn.setTypeface(null, Typeface.BOLD);
                        }

                        fTransaction.show(fg4);

                        break;
                }
                fTransaction.commit();
                m_select_current_types = homepage_nav_top_radioGroup.getCheckedRadioButtonId();
            }
        });

        m_select_current_types = homepage_nav_top_radioGroup.getCheckedRadioButtonId();
        home_page_content = (FrameLayout) findViewById(R.id.home_page_content);

        handlRadio();
        if (homepage_nav_top_goods_radiobtn != null) {
            homepage_nav_top_goods_radiobtn.setTextSize(mContext.getResources().getDimension(R.dimen.nav_menu_select));
            homepage_nav_top_goods_radiobtn.setTypeface(null, Typeface.BOLD);
        }
        handAllFragment();

        Log.d(TAG, "Urlinfor.getmUrlinfor().getLogoImage()=a=: " + Urlinfor.getmUrlinfor().getLogoImage());
        Log.d(TAG, "Urlinfor.getmUrlinfor().getPathsLogoImage()=a=: " + Urlinfor.getmUrlinfor().getPathsLogoImage());

        if (Urlinfor.getmUrlinfor().getLogoImage().length() > 0 && !Urlinfor.getmUrlinfor().getLogoImage().contains("null")) {
            top_logo_image_load.setImageURL(Urlinfor.getmUrlinfor().getPathsLogoImage(), Urlinfor.getmUrlinfor().getLogoImage());
        }
    }


    //隐藏所有Fragment
    private void hideAllFragment(FragmentTransaction fragmentTransaction) {
        if (fg1 != null) fragmentTransaction.hide(fg1);
        if (fg2 != null) fragmentTransaction.hide(fg2);
        if (fg3 != null) fragmentTransaction.hide(fg3);
        if (fg4 != null) fragmentTransaction.hide(fg4);
    }

    private void handAllFragment() {
        FragmentTransaction fTransaction = fManager.beginTransaction();

        if (fg1 == null) {
            fg1 = new GoodFragment();
            fTransaction.add(R.id.home_page_content, fg1);
        }
        if (fg2 == null) {
            fg2 = new OrderFragment();
            fTransaction.add(R.id.home_page_content, fg2);
        }
        if (fg3 == null) {
            fg3 = new HandloutFragment();
            fTransaction.add(R.id.home_page_content, fg3);
        }
        if (fg4 == null) {
            fg4 = new SetsFragment();
            fTransaction.add(R.id.home_page_content, fg4);
        }
        hideAllFragment(fTransaction);
        fTransaction.show(fg1);
        fTransaction.commit();
    }

    private void handlRadio() {
        if (homepage_nav_top_goods_radiobtn != null) {
            homepage_nav_top_goods_radiobtn.setTextSize(mContext.getResources().getDimension(R.dimen.nav_menu_nomal));
            homepage_nav_top_goods_radiobtn.setTypeface(null, Typeface.NORMAL);
        }

        if (homepage_nav_top_order_radiobtn != null) {
            homepage_nav_top_order_radiobtn.setTextSize(mContext.getResources().getDimension(R.dimen.nav_menu_nomal));
            homepage_nav_top_order_radiobtn.setTypeface(null, Typeface.NORMAL);
        }
        if (homepage_nav_top_handl_out_radiobtn != null) {
            homepage_nav_top_handl_out_radiobtn.setTextSize(mContext.getResources().getDimension(R.dimen.nav_menu_nomal));
            homepage_nav_top_handl_out_radiobtn.setTypeface(null, Typeface.NORMAL);
        }
        if (homepage_nav_top_set_radiobtn != null) {
            homepage_nav_top_set_radiobtn.setTextSize(mContext.getResources().getDimension(R.dimen.nav_menu_nomal));
            homepage_nav_top_set_radiobtn.setTypeface(null, Typeface.NORMAL);
        }

    }

    private void handlCurrentTime() {
        mTimeHandlerOne.sendEmptyMessageDelayed(100, 1000);
        // SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat formatter = new SimpleDateFormat("HH:mm");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        String str = formatter.format(curDate);
        home_page_time_text.setText(str);
    }


    /**
     * 隐藏虚拟按键，并且全屏
     */
    protected void hideBottomUIMenu() {
        //隐藏虚拟按键，并且全屏
        if (Build.VERSION.SDK_INT > 11 && Build.VERSION.SDK_INT < 19) { // lower api
            View v = this.getWindow().getDecorView();
            v.setSystemUiVisibility(View.GONE);
        } else if (Build.VERSION.SDK_INT >= 19) {
            //for new api versions.
            View decorView = getWindow().getDecorView();
            int uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_FULLSCREEN;
            decorView.setSystemUiVisibility(uiOptions);
        }

        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_FULLSCREEN);
        getWindow().getDecorView().setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() {
            @Override
            public void onSystemUiVisibilityChange(int visibility) {
                getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY | View.SYSTEM_UI_FLAG_FULLSCREEN);
            }
        });
    }

    public void setClearpupView(String infors) {

        Log.d(TAG, "setClearpupView:==infors==" + infors);
        CleanStatusRecord.getmUrlinfor().setmCleanRunStatus(1);
        SimpleDateFormat formatter2 = new SimpleDateFormat("yyyy-MM-dd");
        long timestamps = System.currentTimeMillis();
        Date curDate1 = new Date(timestamps);//获取当前时间

        String str2 = formatter2.format(curDate1);
        DebugUtils.printDebugInfo(str2);
        CleanStatusRecord.getmUrlinfor().setDetectStartNew(str2);

        if (mClearpupView == null) {
            mClearpupView = new ClearpupView(this);
        }
        mClearpupView.show();


        mClearpupView.initView(infors);
        /*
        AlertDialog.Builder  normalDialog = new AlertDialog.Builder(this);
        normalDialog.setTitle("信息");
        normalDialog.setMessage("延迟单位（ms）");
        normalDialog.create().show();
*/
    }

    //弹窗出料
    public void setSpecifPopuView(HomepageLeftMenuItemData lefta, HomepageGridRightMenuItemData righta, String names, String infors, String infors2) {
        SlovmeData.getSlovmeData().setLefta(lefta);
        SlovmeData.getSlovmeData().setRighta(righta);
//        if (mSpecifPopuView == null) {
//            mSpecifPopuView = new SpecifPopuView(this);
//        }
//        mSpecifPopuView.show();
//        mSpecifPopuView.setNameInfor(names);
//        mSpecifPopuView.setListInfor(infors);
//        mSpecifPopuView.setOutsInfor(infors2);

        if(mSpecifData != null){
            mSpecifData.clear();
        }

        try {
            JSONArray arrys = new JSONArray(infors);
            for (int i = 0; i < arrys.length(); i++) {
                JSONObject atm = arrys.getJSONObject(i);
                if( atm.isNull("id") || atm.isNull("name") || atm.isNull("typeName") ){
                    continue;
                }
                int typeid = atm.optInt("id");
                String typename = atm.optString("name");
                String typeinfor = atm.optString("typeName");
                String cupTypeReserve2 ="1";// atm.optString("cupTypeReserve2");
                String productCode = "";//atm.optString("productCode");
                String errorData="0";
                if(atm.has("errorData")){
                    errorData= atm.optString("errorData");
                }
                String price = atm.optString("price");
                JSONArray content =new  JSONArray();// atm.optJSONArray("children");
                mSpecifData.add(new SpecifData(typeid,typename,typeinfor,cupTypeReserve2,productCode,price,errorData,content.toString() ));

            }
        } catch (JSONException e) {
            e.printStackTrace();

        }
        mOutInfors = infors2 ;

        SpecifData itema =   mSpecifData.get(0);
        Log.d("aaa", "ContentonItemClick: "+itema.getContent());
        String typeOrder = itema.getTypeOrder();
        String typeinfor = itema.getContent();
        Log.d("aaa", "ContentonItemClicktypeinfor: "+typeinfor);

        HomePages.mHomePages.setProduceProgress(itema,names,typeOrder ,mOutInfors);

    }
  //物联网制作
    public void makeOrderDetail(OrderContentData infors) {
        mIsCancels = false;
        setMqProduceProgress(infors, infors.getSecondName() + "-" + infors.getCupType(), infors.getCupType(), infors.getmBeverageNameTag());
    }

    public void deletOrderDetail(OrderContentData infors) {
        mIsCancels = false;
        SlovmeData.getSlovmeData().setOrderContentData(infors);
        Message msg = new Message();
        String str1;
        str1 = "";
        try {


            JSONObject json1 = new JSONObject();
            json1.put("cmd", "del");
            JSONArray arrya1 = new JSONArray();
            JSONObject json2 = new JSONObject();
            json2.put("orderId", infors.getmContentName());
            json2.put("cupNum", infors.getmImgPath());

            arrya1.put(json2);
            json1.put("infor", arrya1);
            str1 = json1.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        cancelMqSales();
        Log.d(TAG, "current str1str1==" + str1);

        msg.what = LOCAL_DEL_DATA;
        msg.obj = str1;
        mMqttHandler.sendMessage(msg);
    }

    public void setMqProduceProgress(OrderContentData infors, String names, String typeOrder, String typeinfor) {

        SlovmeData.getSlovmeData().setOrderContentData(infors);
        mPinsShortage.clear();
        boolean isShort = false;
        boolean isPerid = false;
        String namesInfros = "";
        String peridInfros = "";
        try {
            JSONArray arrycsalls = new JSONArray(typeinfor);
            Log.d(TAG, "setMqProduceProgress:arrycsalls=" + arrycsalls);
            SlovmeData.getSlovmeData().setOutData(arrycsalls);
            JSONArray arrycsall = new JSONArray(typeinfor);

            for (int indexa = 0; indexa < arrycsall.length(); indexa++) {
                JSONObject itema = arrycsall.getJSONObject(indexa);
                int baseid = Integer.parseInt(itema.optString("materialpines"));
                int outdata = Integer.parseInt(itema.optString("setbeverageOutput"));
                MerilData merilData = mPinsMerilData.get(baseid);

                int materialRemind = 0;
                int materialFull = 100;
                if (merilData != null) {
                    materialRemind = Integer.parseInt(merilData.getMaterialRemind());
                    materialFull = Integer.parseInt(merilData.getMaterialFull());
                }
                int usersa = mpinsUserInfors.get(baseid);
                if ((usersa + outdata + materialRemind) >= materialFull) {
                    namesInfros += merilData.getMaterialName() + ";";
                    isShort = true;
                }
                if (juistPinPeriod(baseid)) {
                    peridInfros += merilData.getMaterialName() + ";";
                    isPerid = true;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


        if (isShort) {
            Toast.makeText(mContext, mContext.getResources().getString(R.string.home_page_weight_error_shortage_materials) + namesInfros, Toast.LENGTH_SHORT).show();

            return;
        }
//        if (isPerid) {
//            Toast.makeText(mContext, mContext.getResources().getString(R.string.home_page_weight_error_perid_materials) + peridInfros, Toast.LENGTH_SHORT).show();
//
//            return;
//        }

        mCurrentTypes = 2;
        m_names =names;
        int times = outData(typeOrder, typeinfor);

        try {

            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


        if (mProducePopupView == null) {
            mProducePopupView = new ProducePopupView(mContext);
        }

        mProducePopupView.show();
        mProducePopupView.setNameInfor(names);
        mProducePopupView.setRunTime(times / 1000);

        String str1;
        str1 = "";
        try {


            JSONObject json1 = new JSONObject();
            json1.put("cmd", "del");
            JSONArray arrya1 = new JSONArray();
            JSONObject json2 = new JSONObject();
            json2.put("orderId", infors.getmContentName());
            json2.put("cupNum", infors.getmImgPath());

            arrya1.put(json2);
            json1.put("infor", arrya1);
            str1 = json1.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }

        mTimeQmSalesInfor = str1;
        mTimeQmSalesTime.sendEmptyMessageDelayed(TIME_QM_SALES_DELATE, 1000);


    }

    //正常出料
    public void setProduceProgress(SpecifData typea, String names, String typeOrder, String typeinfor) {
//        if (mProducePopupView == null) {
//            mProducePopupView = new ProducePopupView(mContext);
//        }
//        mProducePopupView.show();
//        mProducePopupView.setNameInfor(names);
//        mProducePopupView.setRunTime(times);
        mIsCancels = false;

        Log.d(TAG, "setProduceProgress:typeinfor=="+typeinfor);
        Log.d(TAG, "setProduceProgress:names=="+names);
        Log.d(TAG, "setProduceProgress:typeOrder=="+typeOrder);
        int weighing_verification_status = DevicesInfors.getDevicesInfors().getWeighing_verification_status();
        DebugUtils.printLogInfo("");
//        if(true){
//            Log.d(TAG, "setProduceProgress:=typeinfor===="+typeinfor);
//            return;
//        }
        mCheckWeighNew = false;
        if (weighing_verification_status == 1) {
            mCheckWeighNew = true;
        }
        if (DevicesInfors.getDevicesInfors().getDevice_type() == 2) {
            boolean isShort = false;
            boolean isPerid = false;
            String namesInfros = "";
            String peridInfros = "";
            DebugUtils.printLogInfo("");
            try {
                JSONArray arrycsalls = new JSONArray(typeinfor);
                SlovmeData.getSlovmeData().setOutData(arrycsalls);
                JSONArray arrycsall = new JSONArray(typeinfor);
                DebugUtils.printLogInfo("");
                for (int indexa = 0; indexa < arrycsall.length(); indexa++) {
                    JSONObject itema = arrycsall.getJSONObject(indexa);
                    Log.d(TAG, "setProduceProgress=1=itema=="+itema.toString() );
                    int materialId = itema.optInt("materialId");
                    Log.d(TAG, "setProduceProgress=1=materialId=="+ String.valueOf(materialId) );
                    DebugUtils.printLogInfo("");
                    Integer baseid =  materialsPins.get(materialId);
                    Log.d(TAG, "setProduceProgress=1=baseid=="+ String.valueOf(baseid) );
                    DebugUtils.printLogInfo("");
                    if(baseid == null || baseid == 0){
                        continue;
                    }
                    Log.d(TAG, "setProduceProgress=1=baseid=2="+ String.valueOf(baseid) );
                    DebugUtils.printLogInfo("");
                    int outdata = itema.optInt("materialValue");
                    MerilData merilData = mPinsMerilData.get(baseid);
                    DebugUtils.printLogInfo("");
                    int materialRemind = 0;
                    int materialFull = 100;
                    if (merilData != null) {
                        materialRemind = Integer.parseInt(merilData.getMaterialRemind());
                        materialFull = Integer.parseInt(merilData.getMaterialFull());
                    }
                    DebugUtils.printLogInfo("");
                    int usersa = mpinsUserInfors.get(baseid);
                    DebugUtils.printLogInfo("usersa="+usersa);
                    DebugUtils.printLogInfo("outdata="+outdata);
                    DebugUtils.printLogInfo("materialRemind="+materialRemind);
                    DebugUtils.printLogInfo("materialFull="+materialFull);
                    DebugUtils.printLogInfo("(usersa + outdata + materialRemind)="+(usersa + outdata + materialRemind));
                    if ((usersa + outdata + materialRemind) >= materialFull) {
                        namesInfros += merilData.getMaterialName() + ";";
                        isShort = true;
                    }
                    if (juistPinPeriod(baseid)) {
                        peridInfros += merilData.getMaterialName() + ";";
                        isPerid = true;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                DebugUtils.printLogInfo("");
            }

            if (isShort) {
                Toast.makeText(mContext, mContext.getResources().getString(R.string.home_page_weight_error_shortage_materials) + namesInfros, Toast.LENGTH_SHORT).show();
                DebugUtils.printLogInfo("");
                return;
            }
//            if (isPerid) {
//                Toast.makeText(mContext, mContext.getResources().getString(R.string.home_page_weight_error_perid_materials) + peridInfros, Toast.LENGTH_SHORT).show();
//                DebugUtils.printLogInfo("");
//                return;
//            }

            Log.d(TAG, "setProduceProgress: typea.getTypeOrder()=" + typea.getTypeOrder());
            Log.d(TAG, "setProduceProgress: typea.getTypename()=" + typea.getTypename());
            Log.d(TAG, "setProduceProgress: typea.getContent()=" + typea.getContent());
            Log.d(TAG, "setProduceProgress: typea.getProductCode()=" + typea.getProductCode());
            Log.d(TAG, "setProduceProgress: typea.getTypeinfor()=" + typea.getTypeinfor());
            Log.d(TAG, "setProduceProgress: typea.getTypeid()=" + typea.getTypeid());
            Log.d(TAG, "setProduceProgress: typea.getPrices()=" + typea.getPrices());
            DebugUtils.printLogInfo("");
            Log.d(TAG, "setProduceProgress: names=" + names);
            Log.d(TAG, "setProduceProgress: typeOrder=" + typeOrder);
            Log.d(TAG, "setProduceProgress: typeinfor=" + typeinfor);
            CartDatas.getCartDatas().setmSpecifData(typea);
            CartDatas.getCartDatas().setmNames(names);
            CartDatas.getCartDatas().setmTypeOrder(typeOrder);
            CartDatas.getCartDatas().setmTypeinfor(typeinfor);
            long currentTime = System.currentTimeMillis();
            String ordernums = Urlinfor.getmUrlinfor().getMdevicenums() + String.valueOf(currentTime / 1000);
            CartDatas.getCartDatas().setmOrdernums(ordernums);
            CartDatas.getCartDatas().getmSpecifData().setPrices(typea.getPrices());
            Intent intent = new Intent(HomePages.this, PayCodes.class);    //切换Login Activity至User Activity
            DebugUtils.printLogInfo("");
            startActivity(intent);
            return;
        }

        DebugUtils.printLogInfo("");
        moutmaterialsNames = names;
        long currentTime = System.currentTimeMillis();
        long allTime = currentTime / 1000;
        String timeNow = new SimpleDateFormat("HH:mm:ss").format(currentTime);
        DebugUtils.printLogInfo("");
        if (weighing_verification_status == 1 && DevicesInfors.getDevicesInfors().jusitVerifyTime(timeNow)) {
            DebugUtils.printLogInfo("");
            moutListArrys.clear();
            mCheckWeighStatus = true;

        } else {
            DebugUtils.printLogInfo("");
//            if(weighing_verification_status == 1){
//
//            }else{
            mCheckWeighStatus = false;

            //    }

        }
        Log.d(TAG, "setProduceProgress: typeinfor=" + typeinfor);
        DebugUtils.printLogInfo("");
        Log.d(TAG, "setProduceProgress: mCheckWeighStatus=" + mCheckWeighStatus);
        SlovmeData.getSlovmeData().setTypea(typea);
        mPinsShortage.clear();
        boolean isShort = false;
        boolean isPerid = false;
        String namesInfros = "";
        String peridInfros = "";
        moutmaterialsArrys.clear();
        ArrayList<JSONArray> outmaterialsArrys = new ArrayList<JSONArray>();
        mOutCurrentAllWeighs = 0;
        Log.d(TAG, "setProduceProgress:==typeinfor==1");
        DebugUtils.printLogInfo("");
        try {
            JSONArray arrycsalls = new JSONArray(typeinfor);
            moutmaterialsInfors = arrycsalls;
            SlovmeData.getSlovmeData().setOutData(arrycsalls);
            JSONArray arrycsall = new JSONArray(typeinfor);
            Log.d(TAG, "setProduceProgress:==typeinfor==arrycsalls="+arrycsalls.toString());
            Log.d(TAG, "setProduceProgress:==arrycsall==2=" + arrycsall);
            DebugUtils.printLogInfo(arrycsall.toString() );
            DebugUtils.printLogInfo( typeinfor  );
            DebugUtils.printLogInfo(arrycsalls.toString() );
            if (arrycsall.length() <= 0) {
                Toast.makeText(mContext, mContext.getResources().getString(R.string.home_page_error_one), Toast.LENGTH_SHORT).show();
                DebugUtils.printLogInfo("");
                return;
            }
            Log.d(TAG, "setProduceProgress:mPinsMerilData.keySet()= " + mPinsMerilData.keySet());
            Log.d(TAG, "setProduceProgress:materialsPin= " + materialsPins.toString() );
            DebugUtils.printLogInfo("");
            for (int indexa = 0; indexa < arrycsall.length(); indexa++) {
                JSONObject itema = arrycsall.getJSONObject(indexa);
                int materialId = itema.optInt("materialId");
                Integer baseid =  materialsPins.get(materialId);
                Log.d(TAG, "setProduceProgress:materialId= " + String.valueOf(materialId) );
                DebugUtils.printLogInfo("");
                if(baseid == null || baseid == 0){
                    continue;
                }
                DebugUtils.printLogInfo("");
                Log.d(TAG, "setProduceProgress:baseid= " + String.valueOf(baseid) );

                JSONArray tempsallsa = new JSONArray();
                tempsallsa.put(itema);
                Log.d(TAG, "setProduceProgress:tempsallsa= " + tempsallsa);
                Log.d(TAG, "setProduceProgress:itema= " + itema);

                DebugUtils.printLogInfo("");
                int outdata = Integer.parseInt(itema.optString("materialValue"));
                Log.d(TAG, "setProduceProgress:baseid= " + baseid);

//                if(!mPinsMerilData.containsKey(baseid)){
//                    Log.d(TAG, "setProduceProgress:baseid=1= " + baseid);
//
//                    continue;
//                }
                DebugUtils.printLogInfo("");
                mOutCurrentAllWeighs += outdata;
                MerilData merilData = mPinsMerilData.get(baseid);
                outmaterialsArrys.add(tempsallsa);
                Log.d(TAG, "setProduceProgress:mCheckWeighStatus=0= " + mCheckWeighStatus);
                findOutmaterials(typea.getTypeid(), baseid, outdata);
                DebugUtils.printLogInfo("");
                if (mCheckWeighStatus) {
                    Log.d(TAG, "setProduceProgress:mCheckWeighStatus=1= " + mCheckWeighStatus);

                    Log.d(TAG, "setProduceProgress:mCheckWeighStatus=2= " + mCheckWeighStatus);
                    DebugUtils.printLogInfo("");
                    MerilData merilDatasa = mPinsMerilData.get(baseid);
                    Log.d(TAG, "setProduceProgress:mCheckWeighStatus=3= " + mCheckWeighStatus);

                    String keysa = "";
                    keysa = String.valueOf(typea.getTypeid()) + "-" + String.valueOf(baseid) + "-" + String.valueOf(outdata);
                    moutListArrys.add(keysa);
                    Log.d(TAG, "setProduceProgress:mCheckWeighStatus=4= " + mCheckWeighStatus);
                    DebugUtils.printLogInfo("");
                    Integer infas1 = moutmaterialsTimesMap.get(keysa);
                    Log.d(TAG, "setProduceProgress:mCheckWeighStatus=4infas1= " + infas1);

                    int timesta = infas1.intValue();
                    Integer numsta = moutmaterialsNumsMap.get(keysa);
                    Log.d(TAG, "setProduceProgress:mCheckWeighStatus=5= " + mCheckWeighStatus);
                    Log.d(TAG, "setProduceProgress:mCheckWeighStatus=5=numsta= " + numsta);
                    DebugUtils.printLogInfo("");
                    if (merilDatasa != null) {
                        String weighing_verification = merilDatasa.getWeighing_verification();
                        int weighing_verificationa = Integer.parseInt(weighing_verification);
                        int temLena = timesta + weighing_verificationa;
                        Log.d(TAG, "setProduceProgress:mCheckWeighStatus=6= " + mCheckWeighStatus);
                        Log.d(TAG, "setProduceProgress:mCheckWeighStatus=6=weighing_verificationa= " + weighing_verificationa);

                        Log.d(TAG, "setProduceProgress:mCheckWeighStatus=6=temLena= " + temLena);
                        Log.d(TAG, "setProduceProgress:mCheckWeighStatus=6=allTime= " + allTime);
                        DebugUtils.printLogInfo("");
                        if (numsta < 3 || (temLena) < (int) allTime) {
                            Log.d(TAG, "setProduceProgress:mCheckWeighStatus=6= " + mCheckWeighStatus);
                            moutmaterialsArrys.add(tempsallsa);
                            DebugUtils.printLogInfo("");
                        }
                    }
                    Log.d(TAG, "setProduceProgress:mCheckWeighStatus=6= " + mCheckWeighStatus);
                    DebugUtils.printLogInfo("");
                    Log.d(TAG, "setProduceProgress:mCheckWeighStatus=6= " + mCheckWeighStatus);

                    Log.d(TAG, "setProduceProgress:moutmaterialsArrys.size()=1= " + moutmaterialsArrys.size());

                }
                DebugUtils.printLogInfo("");
                int materialRemind = 0;
                int materialFull = 100;
                if (merilData != null) {
                    materialRemind = Integer.parseInt(merilData.getMaterialRemind());
                    materialFull = Integer.parseInt(merilData.getMaterialFull());
                }
                int usersa = mpinsUserInfors.get(baseid);
                DebugUtils.printLogInfo("baseid="+baseid);
                DebugUtils.printLogInfo("usersa="+usersa);
                DebugUtils.printLogInfo("outdata="+outdata);
                DebugUtils.printLogInfo("materialRemind="+materialRemind);
                DebugUtils.printLogInfo("materialFull="+materialFull);
                DebugUtils.printLogInfo("(usersa + outdata + materialRemind)="+(usersa + outdata + materialRemind));
                if ((usersa + outdata + materialRemind) >= materialFull) {
                    namesInfros += merilData.getMaterialName() + ";";
                    isShort = true;
                }
                if (juistPinPeriod(baseid)) {
                    peridInfros += merilData.getMaterialName() + ";";
                    isPerid = true;
                }
                DebugUtils.printLogInfo("");
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.d(TAG, "setProduceProgress: error=" + e.getMessage());
            Toast.makeText(mContext, mContext.getResources().getString(R.string.home_page_find_param_error_one_text), Toast.LENGTH_SHORT).show();
            DebugUtils.printLogInfo("");
            return;
        }
        Log.d(TAG, "setProduceProgress: typeinfor==3");
        DebugUtils.printLogInfo("");
        if (isShort) {
            Toast.makeText(mContext, mContext.getResources().getString(R.string.home_page_weight_error_shortage_materials) + namesInfros, Toast.LENGTH_SHORT).show();
            DebugUtils.printLogInfo("");
            return;
        }
//        if (isPerid) {
//            Toast.makeText(mContext, mContext.getResources().getString(R.string.home_page_weight_error_perid_materials) + peridInfros, Toast.LENGTH_SHORT).show();
//            DebugUtils.printLogInfo("");
//            return;
//        }
        Log.d(TAG, "setProduceProgress:moutmaterialsArrys.size()= " + moutmaterialsArrys.size());
        DebugUtils.printLogInfo("");
        Log.d(TAG, "setProduceProgress:moutmaterialsArrys= " + moutmaterialsArrys);
        mCurrentTypes = 1;
        if (moutmaterialsArrys.size() > 0) {
            DebugUtils.printLogInfo("");
            mOutCurrentWeighsInits = 0;
            moutmaterialsArrys = outmaterialsArrys;
            Log.d(TAG, "setProduceProgress: getWeight=1");
            getWeight();
            if (mProducePopupView == null) {
                mProducePopupView = new ProducePopupView(mContext);
            }
            Log.d(TAG, "setProduceProgress: getWeight=2");
            DebugUtils.printLogInfo("");
            mProducePopupView.show();
            mProducePopupView.setNameInfor(names);
            mProducePopupView.setRunTime(100);
            Log.d(TAG, "setProduceProgress: getWeight=3");
            DebugUtils.printLogInfo("");
            // mTimeSalesTime.sendEmptyMessageDelayed(TIME_SALES_DELATE, 1000);
            return;
        } else {
            Log.d(TAG, "setProduceProgress: getWeight=4");
            DebugUtils.printLogInfo("");
            mtypeOrder = typeOrder;
            if (mCheckWeighStatus) {
                Log.d(TAG, "setProduceProgress: getWeight=5");
                DebugUtils.printLogInfo("");
                mOutCurrentWeighsInits = 0;
                // moutmaterialsArrys = outmaterialsArrys;
                Log.d(TAG, "setProduceProgress: getWeight=6");
                DebugUtils.printLogInfo("");
                getWeight();
                Log.d(TAG, "setProduceProgress: getWeight=7");

                return;
            }
        }
        Log.d(TAG, "setProduceProgress: getWeight=8");
        m_names =names;
        int times = outData(typeOrder, typeinfor);
        try {

            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Log.d(TAG, "setProduceProgress: getWeight=9");
        handlOutTeaMachine();
        DebugUtils.printLogInfo("");
        if (moutTeaMachineArrys.size() <= 0) {
            if (mProducePopupView == null) {
                mProducePopupView = new ProducePopupView(mContext);
            }
            Log.d(TAG, "setProduceProgress: getWeight=10");
            DebugUtils.printLogInfo("");
            mProducePopupView.show();
            mProducePopupView.setNameInfor(names);
            mProducePopupView.setRunTime(times / 1000);
            Log.d(TAG, "setProduceProgress: getWeight=11");

            mTimeSalesTime.sendEmptyMessageDelayed(TIME_SALES_DELATE, 1000);
            Log.d(TAG, "setProduceProgress: getWeight=12");
            DebugUtils.printLogInfo("");
        }

    }

    //手动出料
    public void outHandlData(int pins, String outDatas) {
        Log.d(TAG, "outHandlDatapins: " + pins);
        Log.d(TAG, "outHandlData: " + outDatas);
        mIsCancels = false;
        mPinsShortage.clear();

        MerilData merilData = mPinsMerilData.get(pins);
        String names = merilData.getMaterialName();
        int materialRemind = 0;
        int materialFull = 100;
        if (merilData != null) {
            materialRemind = Integer.parseInt(merilData.getMaterialRemind());
            materialFull = Integer.parseInt(merilData.getMaterialFull());
        }
        int usersa = mpinsUserInfors.get(pins);
        if ((usersa + Integer.parseInt(outDatas) + materialRemind) >= materialFull) {
            Toast.makeText(mContext, mContext.getResources().getString(R.string.home_page_weight_error_shortage_materials) + names, Toast.LENGTH_SHORT).show();

            return;
        }
//        if (juistPinPeriod(pins)) {
//            Toast.makeText(mContext, mContext.getResources().getString(R.string.home_page_weight_error_perid_materials) + names, Toast.LENGTH_SHORT).show();
//
//            return;
//        }
        int times = outHandlData(pins, Integer.parseInt(outDatas));
        try {

            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if (mProducePopupView == null) {
            mProducePopupView = new ProducePopupView(mContext);
        }
        mProducePopupView.show();
        mProducePopupView.setNameInfor(names);
        mProducePopupView.setRunTime(times / 1000);
        allowanceViewUpdae();
    }

    //上料排空
    public void setUpInfor(String names, HashMap<Integer, Integer> pinsEmptynfors, int emptyTypes) {
//        if (mProducePopupView == null) {
//            mProducePopupView = new ProducePopupView(mContext);
//        }
//        mProducePopupView.show();
//        mProducePopupView.setNameInfor(names);
//        mProducePopupView.setRunTime(times);
        mIsCancels = false;
        Log.d(TAG, "setUpInfor: ===1");
        boolean isTimes = false;
        mpinsTimesEmptynfors.clear();
        mpinsWeighEmptynfors.clear();
        Log.d(TAG, "setUpInfor: ===2");
        for (int kyes : pinsEmptynfors.keySet()) {
            MerilData merilData = mPinsMerilData.get(kyes);
            String rack_type = "0";
            rack_type = merilData.getRack_type();
            String empty_type = "0";
            empty_type = merilData.getEmpty_type();
            Log.d(TAG, "setUpInfor: ==11=empty_type=" + empty_type);

            //上料 2是打开克重
            if (mEmptyType == 0) {

                if (Integer.parseInt(rack_type) == 2) {

                    String compensate_rack = "0";// 一键上料(g) 补偿克重(g)

                    String rack_2 = "0";//一键上料(g)

                    compensate_rack = merilData.getCompensate_rack();
                    rack_2 = merilData.getRack_2();
                    int weighs = Integer.parseInt(compensate_rack) + Integer.parseInt(rack_2);
                    mpinsWeighEmptynfors.put(kyes, weighs);

                    Log.d(TAG, "setUpInfor: compensate_rack=" + compensate_rack);
                    Log.d(TAG, "setUpInfor: rack_2=" + rack_2);

                } else {
                    Log.d(TAG, "setUpInfor: pinsEmptynfors.get(kyes)=" + pinsEmptynfors.get(kyes));

                    mpinsTimesEmptynfors.put(kyes, pinsEmptynfors.get(kyes));
                    isTimes = true;
                }
            }

            //排空 2是打开克重
            if (mEmptyType == 1) {

                if (Integer.parseInt(empty_type) == 2) {
                    String compensate_empty = "0";// 一键排空(g) 补偿克重(g)

                    String empty_2 = "0";//一键排空(g)
                    compensate_empty = merilData.getCompensate_empty();
                    empty_2 = merilData.getEmpty_2();
                    int weighs = Integer.parseInt(compensate_empty) + Integer.parseInt(empty_2);
                    mpinsWeighEmptynfors.put(kyes, weighs);
                    Log.d(TAG, "setUpInfor: compensate_empty=" + compensate_empty);
                    Log.d(TAG, "setUpInfor: empty_2=" + empty_2);

                } else {
                    Log.d(TAG, "setUpInfor: pinsEmptynfors.get(kyes)=1=" + pinsEmptynfors.get(kyes));

                    mpinsTimesEmptynfors.put(kyes, pinsEmptynfors.get(kyes));
                    isTimes = true;
                }
            }

            Log.d(TAG, "setUpInfor: ==10");
        }
        mEmptyType = emptyTypes;
        mCurrentTypes = 3 + mEmptyType;
        Log.d(TAG, "setUpInfor: ==11=emptyTypes=" + emptyTypes);
        Log.d(TAG, "setUpInfor: ==11=mEmptyType=" + mEmptyType);
        Log.d(TAG, "setUpInfor: ==11=mCurrentTypes=" + mCurrentTypes);

        if (!isTimes) {
            mCurrentWeighsInits = 0;
            getWeight();
            int times = 5 * 1000 * 60;
            Log.d(TAG, "setUpInfor: ==12");

            try {

                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (mProducePopupView == null) {
                mProducePopupView = new ProducePopupView(mContext);
            }
            mProducePopupView.show();
            mProducePopupView.setNameInfor(names);
            mProducePopupView.setRunTime(times / 1000);
            Log.d(TAG, "setUpInfor: ==13");

            return;
        }
        HashMap<Integer, Integer> pinsEmptynfora = new HashMap<Integer, Integer>();
        Log.d(TAG, "setUpInfor: ==14");

        if (mpinsTimesEmptynfors.size() > 0) {
            if (mpinsTimesEmptynfors.size() > 12) {
                int numna = 0;
                ArrayList<Integer> listas1 = new ArrayList<Integer>();
                for (int kyes : mpinsTimesEmptynfors.keySet()) {
                    Log.d(TAG, "setUpInfor: ==15=kyes=" + kyes);

                    pinsEmptynfora.put(kyes, mpinsTimesEmptynfors.get(kyes));
                    Log.d(TAG, "setUpInfor: ==15=kyes=1=" + kyes);

                    numna++;
                    Log.d(TAG, "setUpInfor: ==15=kyes=2=" + kyes);
                    listas1.add(kyes);
                    //  mpinsTimesEmptynfors.remove(kyes);
                    Log.d(TAG, "setUpInfor: ==15=kyes=3=" + kyes);

                    if (numna >= 12) {
                        Log.d(TAG, "setUpInfor: ==15=kyes=4=" + kyes);

                        break;
                    }
                    Log.d(TAG, "setUpInfor: ==15=kyes=6=" + kyes);

                }
                // mpinsTimesEmptynfors.remove(listas1);
                for (int i = 0; i < listas1.size(); i++) {
                    int itema1 = listas1.get(i);
                    Log.d(TAG, "handleMessage: ==7=" + itema1);

                    mpinsTimesEmptynfors.remove(itema1);
                }
            } else {
                for (int kyes : mpinsTimesEmptynfors.keySet()) {
                    pinsEmptynfora.put(kyes, mpinsTimesEmptynfors.get(kyes));
                }
                mpinsTimesEmptynfors.clear();
            }

        }
        Log.d(TAG, "setUpInfor: ==15");


        int times = outUpData(pinsEmptynfora);
        Log.d(TAG, "setUpInfor: ==16");

        try {

            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if (mProducePopupView == null) {
            mProducePopupView = new ProducePopupView(mContext);
        }
        mProducePopupView.show();
        mProducePopupView.setNameInfor(names);
        mProducePopupView.setRunTime(times / 1000);
        allowanceViewUpdae();
        Log.d(TAG, "setUpInfor: ==17");

    }

    //清洗指令
    public void clearCmd(ArrayList<ClearItem> lista) {
        int lens = 0;
        int lena = 0;
        int timeAll = 0;
        boolean isCricle = false;


        byte tempb = 0;
        byte[] buffer = new byte[1024];

        buffer[0] = 'W';
        buffer[1] = 'X';

        buffer[2] = 0x01;
        buffer[3] = (byte) m_frame_id;
        buffer[4] = 0x00;

        buffer[5] = 0x01;
        buffer[6] = 0x70;
        int index = 0;
        int nmbera = 0;
        int indexa = 0;

        // for (indexa = 0; indexa < arrycsall.length(); indexa++) {
        indexa = 0;
        Log.d(TAG, "clearCmd: lista==" + lista.size());
        ClearItem clearItema = lista.get(0);
        buffer[8] = (byte) getPinReal(Integer.parseInt(clearItema.getPins()));
        buffer[9] = (byte) Integer.parseInt(clearItema.getDirts());
        buffer[10] = (byte) Integer.parseInt(clearItema.getSpeeds());
        buffer[11] = (byte) Integer.parseInt(clearItema.getSpeeds());
        updatePinPeriod(Integer.parseInt(clearItema.getPins()));

        for (int keyas = 1; keyas < lista.size(); keyas++) {
            ClearItem clearItem = lista.get(keyas);
            int baseid = getPinReal(Integer.parseInt(clearItem.getPins()));
            updatePinPeriod(baseid);

            Log.d(TAG, "clearCmd: baseid==" + baseid);
            int outdata = Integer.parseInt(clearItem.getRunTime());
            int timeas = outdata * 1000;

            MerilData merilData = mPinsMerilData.get(baseid);
            buffer[12 + 5 * indexa] = (byte) getPinReal(baseid);//(byte) (tracks & 0xFF);
            buffer[13 + 5 * indexa] = (byte) Integer.parseInt(clearItem.getDirts());


            buffer[14 + 5 * indexa] = (byte) ((timeas >> 16) & 0xFF);

            buffer[15 + 5 * indexa] = (byte) ((timeas >> 8) & 0xFF);

            buffer[16 + 5 * indexa] = (byte) ((timeas) & 0xFF);

            indexa++;
        }
        nmbera = 4;
        nmbera += 5 * indexa;
        index += nmbera;


        lens = index;
        buffer[7] = (byte) lens;
        for (int i = 0; i <= 7 + index; i++) {

            tempb += buffer[i];
        }
        buffer[8 + index] = tempb;

        lena = 9 + index;
        String tempa = new String(buffer, 0, lena);
        String inforh = "";
        for (int i = 0; i < lena; i++) {

            String temp = Integer.toHexString(buffer[i] & 0xFF);
            if (temp.length() == 1) {
                temp = "0" + temp;
            }
            inforh = inforh + temp;
        }
        Log.d("findCurrentStatushssaa=", inforh);

        if (mSerialPort != null) {
            mBuffStr = new byte[1024 * 3];
            m_AllLength = 0;
            mSerialPortUtils.sendByteSerialLenPort(buffer, 0, lena);

            return;
        }

        return;
    }
/*
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode <= 6) {
            return super.dispatchKeyEvent(event);
        }
        if (mScanGun.isMaybeScanning(keyCode, event)) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        // 拦截物理键盘事件
        if (!isHandleKey && event.getKeyCode() > 6) {
            if (event.getAction() == KeyEvent.ACTION_DOWN) {
                this.onKeyDown(event.getKeyCode(), event);
                return true;

            } else if (event.getAction() == KeyEvent.ACTION_UP) {
                this.onKeyUp(event.getKeyCode(), event);
                return true;
            }
            return true;
        }
        return super.dispatchKeyEvent(event);
    }
    */

    @Override
    public void onResume() {

        super.onResume();

    }


    //物联网
    private void initRequestSourceData() {

    }

    public void getReconnetData() {

        new Thread(new Runnable() {

            @Override
            public void run() {
                String strUrl = Urlinfor.getmUrlinfor().getMkesales();
                Log.d("aaaaa", "strUrlstrUrl=aa=" + strUrl);
                URL url = null;
                try {
                    long currentTime = System.currentTimeMillis();
                    String timeNow = new SimpleDateFormat("yyyy-MM-dd").format(currentTime);
                    url = new URL(strUrl);
                    HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
                    urlConn.setDoInput(true);
                    urlConn.setDoOutput(true);
                    urlConn.setRequestMethod("POST");
                    urlConn.setUseCaches(false);
                    urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    urlConn.setRequestProperty("Charset", "utf-8");
                    /*
                    if (urlConn instanceof HttpsURLConnection) {
                        try {
                            SSLContext sslContext = HttpsUtil.getSSLContextWithCer();

                            if (sslContext != null) {
                                SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
                                ((HttpsURLConnection) urlConn).setDefaultSSLSocketFactory(sslSocketFactory);

                            }
                        } catch (Exception e) {
                            e.printStackTrace();

                        }

                    }

                     */
                    urlConn.connect();

                    Log.d("aaaaa", "shopCode:==" + Urlinfor.getmUrlinfor().getShopInformationNo());
                    DataOutputStream dop = new DataOutputStream(urlConn.getOutputStream());
                    // dop.writeBytes("device_no=" + Urlinfor.getmUrlinfor().getMdevicenums());
                    dop.writeBytes("shopCode=" + Urlinfor.getmUrlinfor().getShopInformationNo());

                    dop.flush();
                    dop.close();
                    BufferedReader bufferReader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
                    String result = "";
                    String readline = null;
                    while ((readline = bufferReader.readLine()) != null) {
                        result += readline;
                    }
                    bufferReader.close();
                    urlConn.disconnect();
                    //  String a = result.substring(0,result.length()/ 3);
                    //  String b= result.substring(result.length()/ 3,result.length()*2/ 3);
                    //  String c= result.substring(result.length()*2/ 3,result.length());
                    Log.d("aaaaa", "minqq=abc=" + result);
                    //   Log.d("aaaaa", "minqq=aa=" + a);

                    // Log.d("aaaaa", "minqq=aaa=" + b);
                    // Log.d("aaaaa", "minqq=aaaaaa=" + c);

                    if (result.length() > 0) {
                        String resulta = result;

                        Message msg = new Message();
                        String str1;
                        str1 = resulta;
                        msg.what = CONNECT_RECT_DATA;
                        msg.obj = str1;
                        mMqttRectHandler.sendMessage(msg);
                    } else {


                    }


                } catch (IOException e) {

                    Log.d("aaaaa", "222=");

                    e.printStackTrace();
                }

            }
        }).start();//这个start()方法不要忘记了

    }

    private void handlReconnetData(String currentcont) {
        if (fg2 != null) {
            fg2.clearItem();
            String inforMakes = currentcont;
            String infors = ContentInfor.getmUrlinfor().getInforMenus();
            try {

                Log.d(TAG, "handlMqttData=inforMakes=" + inforMakes);
                JSONArray infor = new JSONArray(inforMakes);
                JSONArray jsonArrya = new JSONArray(infors);
                for (int m = 0; m < infor.length(); m++) {
                    for (int i = 0; i < jsonArrya.length(); i++) {
                        JSONObject aitema = jsonArrya.getJSONObject(i);
                        String firstMenuid = aitema.opt("firstMenuid").toString();
                        String firstMenuNames = aitema.opt("firstMenuNames").toString();
                        JSONArray secondMenu = aitema.optJSONArray("children");

                        for (int j = 0; j < secondMenu.length(); j++) {
                            JSONObject itema = secondMenu.getJSONObject(j);

                            String secondMenuid = itema.opt("secondMenuid").toString();
                            String secondMenuNames = itema.opt("secondMenuNames").toString();
                            String secondMenuReserve = itema.opt("secondMenuReserve").toString();
                            JSONArray childrenb = itema.optJSONArray("children");
                            for (int k = 0; k < childrenb.length(); k++) {
                                JSONObject atm = childrenb.getJSONObject(k);
                                Log.d(TAG, "handlMqttData: atm==" + atm.toString());
                                Log.d(TAG, "handlMqttData: Urlinfor.getmUrlinfor().getShopInformationNo()==" + Urlinfor.getmUrlinfor().getShopInformationNo());


                                int typeid = atm.optInt("cupTypeid");
                                String typename = atm.optString("cupTypeNames");
                                String errorData = "0";
                                if (atm.has("errorData")) {
                                    errorData = atm.optString("errorData");
                                }
                                String typeinfor = atm.optString("cupTypeReserve");
                                String cupTypeReserve2 = atm.optString("cupTypeReserve2");
                                String productCode = atm.optString("productCode");

                                JSONObject atmb = infor.getJSONObject(m);
                                Log.d(TAG, "handlMqttData: atmb==" + atmb.toString());
                                String orderId = atmb.optString("orderNumbers");
                                String orderTime = atmb.optString("orderTime");
                                String shopCode = atmb.optString("shopCode");
                                String cupNum = atmb.optString("cupNumbers");
                                Log.d(TAG, "handlMqttData: shopCode==" + shopCode);

                                String productCodea = atmb.optString("cupType");
                                Log.d(TAG, "handlMqttData: productCodea=1=" + productCodea);
                                Log.d(TAG, "handlMqttData: productCode=1=" + productCode);

                                if (productCode.length() > 0 && productCodea.length() > 0 && productCode.equals(productCodea) && shopCode.equals(Urlinfor.getmUrlinfor().getShopInformationNo())) {
                                    JSONArray content = atm.optJSONArray("children");
                                    Log.d(TAG, "handlMqttData: productCode==" + productCode);

                                    if (fg2 != null) {

                                        String contentName = cupNum;
                                        String orderNumber = orderId;

                                        String firstName = firstMenuid;
                                        String secondName = secondMenuNames;
                                        String cupType = typename;
                                        String beverageNameTag = cupTypeReserve2;
                                        String orderDetail = content.toString();
                                        String cupTypeids = String.valueOf(typeid);

                                        fg2.addItem(new OrderContentData(contentName,
                                                orderNumber, orderTime, firstName,
                                                secondName, cupType, beverageNameTag,
                                                orderDetail, firstMenuid, secondMenuid,
                                                cupTypeids, secondMenuReserve, "", errorData));


                                    }

                                }


                            }
                        }
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();


            }


        }

    }

    private void mqtt_startReconnect() {
        scheduler = Executors.newSingleThreadScheduledExecutor();
        scheduler.scheduleAtFixedRate(new Runnable() {

            @Override
            public void run() {
                if (!client.isConnected()) {


                    if (mqIsInist) {
                        if (!mqIsRect) {
                            mqIsRect = true;
                            Message msg = new Message();
                            msg.what = CONNECT_FAILURE;
                            mMqttHandler.sendMessage(msg);
                        }
                    }
                    mqtt_connect();
                } else {
                    if (mqIsInist) {
                        if (mqIsRect) {
                            mqIsRect = false;
                            //  getReconnetData();

                        }

                    }
                }
            }
        }, 0 * 1000, 5 * 1000, TimeUnit.MILLISECONDS);
    }

    private void mqtt_connect() {
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    client.connect(options);
                    Message msg = new Message();
                    msg.what = CONNECT_SUCCESS;
                    mMqttHandler.sendMessage(msg);
                } catch (Exception e) {
                    e.printStackTrace();
//                    Message msg = new Message();
//                    msg.what = CONNECT_FAILURE;
//                    mMqttHandler.sendMessage(msg);
                }
            }
        }).start();
        mqIsInist = true;
    }

    private void mqtt_init() {
        //  Toast.makeText(mContext, myTopic , Toast.LENGTH_SHORT).show();
        Log.d("aaaaa", "myTopicmyTopicmyTopic =1=" + myTopic);
        Log.d("aaaaa", "myTopicmyTopicmyhost =1=" + host);
        mdeiveid = Urlinfor.getmUrlinfor().getMdevicenums() + Urlinfor.getmUrlinfor().getShopInformationId();// mVersion;
        try {
            //host为主机名，test为clientid即连接MQTT的客户端ID，一般以客户端唯一标识符表示，MemoryPersistence设置clientid的保存形式，默认为以内存保存
            client = new MqttClient(host, mdeiveid,
                    new MemoryPersistence());
            //MQTT的连接设置
            options = new MqttConnectOptions();
            //设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录，这里设置为true表示每次连接到服务器都以新的身份连接
            options.setCleanSession(true);
            //设置连接的用户名
            options.setUserName(userName);
            //设置连接的密码
            options.setPassword(passWord.toCharArray());
            // 设置超时时间 单位为秒
            options.setConnectionTimeout(10);
            // 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送个消息判断客户端是否在线，但这个方法并没有重连的机制
            options.setKeepAliveInterval(20);
            //设置回调
            client.setCallback(new MqttCallback() {

                @Override
                public void connectionLost(Throwable cause) {
                    //连接丢失后，一般在这里面进行重连
                    System.out.println("connectionLost----------");
                }

                @Override
                public void deliveryComplete(IMqttDeliveryToken token) {
                    //publish后会执行到这里
                    System.out.println("deliveryComplete---------"
                            + token.isComplete());
                }

                @Override
                public void messageArrived(String topicName, MqttMessage message)
                        throws Exception {
                    //subscribe后得到的消息会执行到这里面
                    System.out.println("messageArrived----------");
                    Log.d(TAG, "current topicName=2=" + topicName);
                    if (topicName.equals(myTopic + Urlinfor.getmUrlinfor().getMysqlName())) {
                        Message msg = new Message();
                        String str1;
                        str1 = message.toString();

                        Log.d(TAG, "current str1str1==" + str1);

                        msg.what = CONNECT_CONTENT;
                        msg.obj = str1;
                        mMqttHandler.sendMessage(msg);
                    }
                    if (topicName.equals(myTopic + Urlinfor.getmUrlinfor().getMysqlName() + Urlinfor.getmUrlinfor().getShopInformationId())) {
                        Message msg = new Message();
                        String str1;
                        str1 = message.toString();
                        Log.d(TAG, "current str1str1=2=" + str1);

                        msg.what = CONNECT_CONTENT;
                        msg.obj = str1;
                        mMqttHandler.sendMessage(msg);
                    }
                    if (topicName.equals(myTopic + Urlinfor.getmUrlinfor().getMysqlName() + Urlinfor.getmUrlinfor().getMdevicenums())) {
                        Message msg = new Message();
                        String str1;
                        str1 = message.toString();
                        Log.d(TAG, "current str1str1=23=" + str1);

                        msg.what = CONNECT_DEVICE_STATUS;
                        msg.obj = str1;
                        mMqttHandler.sendMessage(msg);
                    }
                    if (topicName.equals(myTopic + Urlinfor.getmUrlinfor().getShopInformationId() + Urlinfor.getmUrlinfor().getMdevicenums())) {
                        Message msg = new Message();
                        String str1;
                        str1 = message.toString();
                        Log.d(TAG, "current str1str1=2=" + str1);

                        msg.what = CONNECT_CMD;
                        msg.obj = str1;
                        mMqttHandler.sendMessage(msg);
                    }

                    //String str2 = new String(str1.getBytes("GBK"),"UTF-8");
                    //edt_subscibe_message.setText(str2.toCharArray(), 0, str2.length());

                }
            });


//			connect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void mqtt_handl() {
        //  Toast.makeText(mContext, "myTopic mqtt_handl="+myTopic , Toast.LENGTH_SHORT).show();
        //
        mqtt_init();
        mqtt_startReconnect();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mBdwrite.close();
        mBdread.close();


    }
    //正常出料
    public int outSecondsData(String typeOrder, String typeinfor) {
        Log.d(TAG, "outData:typeOrder ==" + typeOrder);
        Log.d(TAG, "outData:typeinfor ==" + typeinfor);

        int lens = 0;
        int lena = 0;
        int timeAll = 0;
        boolean isCricle = false;
        if (typeOrder.length() > 0 && Integer.parseInt(typeOrder) == 1) {
            isCricle = true;
        }

        byte tempb = 0;
        byte[] buffer = new byte[1024];

        buffer[0] = 'W';
        buffer[1] = 'X';

        buffer[2] = 0x01;
        buffer[3] = (byte) m_frame_id;
        buffer[4] = 0x00;

        buffer[5] = 0x01;
        buffer[6] = 0x62;
        int index = 0;
        int nmbera = 0;
        int indexa = 0;
        int indexc = 0;
        Log.d(TAG, "outData: " + typeinfor);


        try {

            JSONArray arrycsall = new JSONArray(typeinfor);
            if (isCricle) {
                for (indexa = 0,indexc = 0; indexc  < arrycsall.length();indexc ++) {
                    JSONObject itema = arrycsall.getJSONObject(indexc);
                    int baseid = Integer.parseInt(itema.optString("materialpines"));
                    if (baseid >= 1000) {
                        continue;
                    }
                    updatePinPeriod(baseid);
                    int outdata = Integer.parseInt(itema.optString("setbeverageOutput"));
                    int usersa = mpinsUserInfors.get(baseid);
                    updateAllowance(baseid, usersa + outdata);
                    float speeda = (float) 1.0;
                    String inforSpeeda = "";
                    if (mCheckWeighStatus) {
                        Log.d(TAG, "outData: mCheckWeighStatus=1=" + mCheckWeighStatus);
                        Log.d(TAG, "outData: moutmaterialsSpeedMap=2=" + moutmaterialsSpeedMap);

                        inforSpeeda = String.valueOf(SlovmeData.getSlovmeData().getTypea().getTypeid()) + "-" + String.valueOf(baseid) + "-" + String.valueOf(outdata);
                        Log.d(TAG, "outData: mCheckWeighStatus=2=" + inforSpeeda);

                        if (moutmaterialsSpeedMap.containsKey(inforSpeeda)) {
                            speeda = moutmaterialsSpeedMap.get(inforSpeeda);
                            float tempa1 = mPinsSpeeds.get(baseid);
                            double absDouble = Math.abs(tempa1 - speeda);
                            if (absDouble >= 15) {
                                speeda = tempa1;
                            }
                            Log.d(TAG, "outData: speeda=3=" + speeda);
                            if (speeda <= 0.5) {
                                speeda = tempa1; //mPinsSpeeds.get(baseid);
                                Log.d(TAG, "outData: speeda=4s=" + speeda);

                            }
                        } else {
                            speeda = mPinsSpeeds.get(baseid);
                            Log.d(TAG, "outData: speeda=4=" + speeda);

                        }

                    } else {
                        if (mCheckWeighNew) {
                            inforSpeeda = String.valueOf(SlovmeData.getSlovmeData().getTypea().getTypeid()) + "-" + String.valueOf(baseid) + "-" + String.valueOf(outdata);
                            Log.d(TAG, "outData: mCheckWeighStatus=2s=" + inforSpeeda);

                            if (moutmaterialsSpeedMap.containsKey(inforSpeeda)) {
                                speeda = moutmaterialsSpeedMap.get(inforSpeeda);
                                float tempa1 = mPinsSpeeds.get(baseid);
                                double absDouble = Math.abs(tempa1 - speeda);
                                if (absDouble >= 15) {
                                    speeda = tempa1;
                                }
                                Log.d(TAG, "outData: speeda=3s=" + speeda);
                                if (speeda <= 0.5) {
                                    speeda = mPinsSpeeds.get(baseid);
                                    Log.d(TAG, "outData: speeda=4s=" + speeda);

                                }
                            } else {
                                speeda = mPinsSpeeds.get(baseid);
                                Log.d(TAG, "outData: speeda=4s=" + speeda);

                            }
                        } else {
                            speeda = mPinsSpeeds.get(baseid);

                        }
                        Log.d(TAG, "outData: speeda=5=" + speeda);

                    }
                    Log.d(TAG, "outData: inforSpeeda=" + inforSpeeda);

                    Log.d(TAG, "outData: speeda=" + speeda);
                    float speedb = outdata * 1000 / speeda;
                    int timeas = (int) speedb;
                    Log.d(TAG, "outData: timeas=" + timeas);

                    MerilData merilData = mPinsMerilData.get(baseid);
                    if (!(mCheckWeighStatus || mCheckWeighNew)) {
                        timeas += Integer.parseInt(merilData.getCompensate());
                    }

                    buffer[9 + 8 * indexa] = (byte) getPinReal(baseid);//(byte) (tracks & 0xFF);
                    buffer[10 + 8 * indexa] = (byte) Integer.parseInt(merilData.getMaterialDrit());

                    buffer[11 + 8 * indexa] = (byte) Integer.parseInt(merilData.getMaterialCricle());
                    buffer[12 + 8 * indexa] = (byte) Integer.parseInt(merilData.getMaterialCricle());

                    buffer[13 + 8 * indexa] = (byte) ((timeas >> 16) & 0xFF);
                    buffer[14 + 8 * indexa] = (byte) ((timeas >> 8) & 0xFF);

                    buffer[15 + 8 * indexa] = (byte) ((timeas) & 0xFF);
                    timeAll += timeas;
                    index += 7;
                    buffer[8 + 8 * indexa] = (byte) 7;//(byte) ((tracks >> 8) & 0xFF);
                    nmbera += 7 * (indexa + 1) + 1;
                    index += 1;

                    indexa++;
                }

            } else {
                for (indexa = 0,indexc = 0; indexc  < arrycsall.length();indexc ++) {
                    JSONObject itema = arrycsall.getJSONObject(indexc);
                    int baseid = Integer.parseInt(itema.optString("materialpines"));
                    if (baseid >= 1000) {
                        continue;
                    }

                    updatePinPeriod(baseid);
                    int outdata = Integer.parseInt(itema.optString("setbeverageOutput"));
                    int usersa = mpinsUserInfors.get(baseid);
                    updateAllowance(baseid, usersa + outdata);
                    float speeda = (float) 1.0;
                    String inforSpeeda = "";
                    if (mCheckWeighStatus) {
                        Log.d(TAG, "outData: mCheckWeighStatus=1=" + mCheckWeighStatus);
                        Log.d(TAG, "outData: moutmaterialsSpeedMap=2=" + moutmaterialsSpeedMap);

                        inforSpeeda = String.valueOf(SlovmeData.getSlovmeData().getTypea().getTypeid()) + "-" + String.valueOf(baseid) + "-" + String.valueOf(outdata);
                        Log.d(TAG, "outData: mCheckWeighStatus=2=" + inforSpeeda);

                        if (moutmaterialsSpeedMap.containsKey(inforSpeeda)) {
                            speeda = moutmaterialsSpeedMap.get(inforSpeeda);
                            float tempa1 = mPinsSpeeds.get(baseid);
                            double absDouble = Math.abs(tempa1 - speeda);
                            if (absDouble >= 15) {
                                speeda = tempa1;
                            }
                            Log.d(TAG, "outData: speeda=3=" + speeda);
                            if (speeda <= 0.5) {
                                speeda = mPinsSpeeds.get(baseid);
                                Log.d(TAG, "outData: speeda=4s=" + speeda);

                            }

                        } else {
                            speeda = mPinsSpeeds.get(baseid);
                            Log.d(TAG, "outData: speeda=4=" + speeda);

                        }

                    } else {
                        if (mCheckWeighNew) {
                            inforSpeeda = String.valueOf(SlovmeData.getSlovmeData().getTypea().getTypeid()) + "-" + String.valueOf(baseid) + "-" + String.valueOf(outdata);
                            Log.d(TAG, "outData: mCheckWeighStatus=2s=" + inforSpeeda);

                            if (moutmaterialsSpeedMap.containsKey(inforSpeeda)) {
                                speeda = moutmaterialsSpeedMap.get(inforSpeeda);
                                float tempa1 = mPinsSpeeds.get(baseid);
                                double absDouble = Math.abs(tempa1 - speeda);
                                if (absDouble >= 15) {
                                    speeda = tempa1;
                                }
                                Log.d(TAG, "outData: speeda=3s=" + speeda);
                                if (speeda <= 0.5) {
                                    speeda = mPinsSpeeds.get(baseid);
                                    Log.d(TAG, "outData: speeda=4s=" + speeda);

                                }
                            } else {
                                speeda = mPinsSpeeds.get(baseid);
                                Log.d(TAG, "outData: speeda=4s=" + speeda);

                            }
                        } else {
                            speeda = mPinsSpeeds.get(baseid);

                        }
                        Log.d(TAG, "outData: speeda=5=" + speeda);

                    }
                    float speedb = outdata * 1000 / speeda;
                    int timeas = (int) speedb;
                    MerilData merilData = mPinsMerilData.get(baseid);
                    //  timeas += Integer.parseInt(merilData.getCompensate());
                    if (!(mCheckWeighStatus || mCheckWeighNew)) {
                        timeas += Integer.parseInt(merilData.getCompensate());
                    }

                    if (timeas > timeAll) {
                        timeAll = timeas;
                    }

                    buffer[9 + nmbera + 7 * indexa] = (byte) getPinReal(baseid);//(byte) (tracks & 0xFF);
                    buffer[10 + nmbera + 7 * indexa] = (byte) Integer.parseInt(merilData.getMaterialDrit());

                    buffer[11 + nmbera + 7 * indexa] = (byte) Integer.parseInt(merilData.getMaterialCricle());
                    buffer[12 + nmbera + 7 * indexa] = (byte) Integer.parseInt(merilData.getMaterialCricle());

                    buffer[13 + nmbera + 7 * indexa] = (byte) ((timeas >> 16) & 0xFF);

                    buffer[14 + nmbera + 7 * indexa] = (byte) ((timeas >> 8) & 0xFF);

                    buffer[15 + nmbera + 7 * indexa] = (byte) ((timeas) & 0xFF);
                    index += 7;

                    indexa++;
                }
                buffer[8 + nmbera] = (byte) (7 * indexa);//(byte) ((tracks >> 8) & 0xFF);
                nmbera += 7 * indexa + 1;
                index += 1;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        Log.d(TAG, "outData--moutTeaMachineArrys=" + moutTeaMachineArrys.toString());

        lens = index;
        buffer[7] = (byte) lens;
        for (int i = 0; i <= 7 + index; i++) {

            tempb += buffer[i];
        }
        buffer[8 + index] = tempb;

        lena = 9 + index;
        String tempa = new String(buffer, 0, lena);
        String inforh = "";
        for (int i = 0; i < lena; i++) {

            String temp = Integer.toHexString(buffer[i] & 0xFF);
            if (temp.length() == 1) {
                temp = "0" + temp;
            }
            inforh = inforh + temp;
        }
        Log.d("findCurrentStatushssaa=", inforh);

        if (mSerialPort != null) {
            mBuffStr = new byte[1024 * 3];
            m_AllLength = 0;
            mSerialPortUtils.sendByteSerialLenPort(buffer, 0, lena);

            return timeAll;
        }

        return timeAll;
    }

    //正常出料
    public int outData(String typeOrder, String typeinfor) {
        Log.d(TAG, "outData:typeOrder ==" + typeOrder);
        Log.d(TAG, "outData:typeinfor ==" + typeinfor);
//        if(true){
//            return 1000;
//        }
        m_typeOrder = typeOrder;
        m_typeinfor = typeinfor;
        int lens = 0;
        int lena = 0;
        int timeAll = 0;
        boolean isCricle = false;
        if (typeOrder.length() > 0 && Integer.parseInt(typeOrder) == 1) {
            isCricle = true;
        }
        if (moutTeaMachineArrys != null) {
            moutTeaMachineArrys.clear();
        }

        byte tempb = 0;
        byte[] buffer = new byte[1024];

        buffer[0] = 'W';
        buffer[1] = 'X';

        buffer[2] = 0x01;
        buffer[3] = (byte) m_frame_id;
        buffer[4] = 0x00;

        buffer[5] = 0x01;
        buffer[6] = 0x62;
        int index = 0;
        int nmbera = 0;
        int indexa = 0;
        int indexc = 0;
        Log.d(TAG, "outData: " + typeinfor);

        Log.d(TAG, "outData:=materialsPins="+materialsPins.toString() );
        try {

            JSONArray arrycsall = new JSONArray(typeinfor);
            if (isCricle) {
                for (indexa = 0,indexc = 0; indexc  < arrycsall.length();indexc ++) {
                    JSONObject itema = arrycsall.getJSONObject(indexc);

                    int materialId = itema.optInt("materialId");
                    Log.d(TAG, "outData:=materialId="+String.valueOf(materialId) );
                    Integer baseid =  materialsPins.get(materialId);

                    if(baseid == null || baseid == 0){
                        continue;
                    }

                    if (baseid >= 1000) {
                        moutTeaMachineArrys.add(baseid);
                        continue;
                    }
                    updatePinPeriod(baseid);
                    int outdata = itema.optInt("materialValue");
                    int usersa = mpinsUserInfors.get(baseid);
                    updateAllowance(baseid, usersa + outdata);
                    float speeda = (float) 1.0;
                    String inforSpeeda = "";
                    if (mCheckWeighStatus) {
                        Log.d(TAG, "outData: mCheckWeighStatus=1=" + mCheckWeighStatus);
                        Log.d(TAG, "outData: moutmaterialsSpeedMap=2=" + moutmaterialsSpeedMap);

                        inforSpeeda = String.valueOf(SlovmeData.getSlovmeData().getTypea().getTypeid()) + "-" + String.valueOf(baseid) + "-" + String.valueOf(outdata);
                        Log.d(TAG, "outData: mCheckWeighStatus=2=" + inforSpeeda);

                        if (moutmaterialsSpeedMap.containsKey(inforSpeeda)) {
                            speeda = moutmaterialsSpeedMap.get(inforSpeeda);
                            float tempa1 = mPinsSpeeds.get(baseid);
                            double absDouble = Math.abs(tempa1 - speeda);
                            if (absDouble >= 15) {
                                speeda = tempa1;
                            }
                            Log.d(TAG, "outData: speeda=3=" + speeda);
                            if (speeda <= 0.5) {
                                speeda = tempa1; //mPinsSpeeds.get(baseid);
                                Log.d(TAG, "outData: speeda=4s=" + speeda);

                            }
                        } else {
                            speeda = mPinsSpeeds.get(baseid);
                            Log.d(TAG, "outData: speeda=4=" + speeda);

                        }

                    } else {
                        if (mCheckWeighNew) {
                            inforSpeeda = String.valueOf(SlovmeData.getSlovmeData().getTypea().getTypeid()) + "-" + String.valueOf(baseid) + "-" + String.valueOf(outdata);
                            Log.d(TAG, "outData: mCheckWeighStatus=2s=" + inforSpeeda);

                            if (moutmaterialsSpeedMap.containsKey(inforSpeeda)) {
                                speeda = moutmaterialsSpeedMap.get(inforSpeeda);
                                float tempa1 = mPinsSpeeds.get(baseid);
                                double absDouble = Math.abs(tempa1 - speeda);
                                if (absDouble >= 15) {
                                    speeda = tempa1;
                                }
                                Log.d(TAG, "outData: speeda=3s=" + speeda);
                                if (speeda <= 0.5) {
                                    speeda = mPinsSpeeds.get(baseid);
                                    Log.d(TAG, "outData: speeda=4s=" + speeda);

                                }
                            } else {
                                speeda = mPinsSpeeds.get(baseid);
                                Log.d(TAG, "outData: speeda=4s=" + speeda);

                            }
                        } else {
                            speeda = mPinsSpeeds.get(baseid);

                        }
                        Log.d(TAG, "outData: speeda=5=" + speeda);

                    }
                    Log.d(TAG, "outData: inforSpeeda=" + inforSpeeda);

                    Log.d(TAG, "outData: speeda=" + speeda);
                    float speedb = outdata * 1000 / speeda;
                    int timeas = (int) speedb;
                    Log.d(TAG, "outData: timeas=" + timeas);

                    MerilData merilData = mPinsMerilData.get(baseid);
                    if (!(mCheckWeighStatus || mCheckWeighNew)) {
                        timeas += Integer.parseInt(merilData.getCompensate());
                    }

                    buffer[9 + 8 * indexa] = (byte) getPinReal(baseid);//(byte) (tracks & 0xFF);
                    buffer[10 + 8 * indexa] = (byte) Integer.parseInt(merilData.getMaterialDrit());

                    buffer[11 + 8 * indexa] = (byte) Integer.parseInt(merilData.getMaterialCricle());
                    buffer[12 + 8 * indexa] = (byte) Integer.parseInt(merilData.getMaterialCricle());

                    buffer[13 + 8 * indexa] = (byte) ((timeas >> 16) & 0xFF);
                    buffer[14 + 8 * indexa] = (byte) ((timeas >> 8) & 0xFF);

                    buffer[15 + 8 * indexa] = (byte) ((timeas) & 0xFF);
                    timeAll += timeas;
                    index += 7;
                    buffer[8 + 8 * indexa] = (byte) 7;//(byte) ((tracks >> 8) & 0xFF);
                    nmbera += 7 * (indexa + 1) + 1;
                    index += 1;

                    indexa++;
                }

            } else {
                for (indexa = 0,indexc = 0; indexc  < arrycsall.length();indexc ++) {
                    JSONObject itema = arrycsall.getJSONObject(indexc);

                    int materialId = itema.optInt("materialId");

                    Integer baseid =  materialsPins.get(materialId);

                    if(baseid == null || baseid == 0){
                        continue;
                    }


                    if (baseid >= 1000) {
                        moutTeaMachineArrys.add(baseid);
                        continue;
                    }

                    updatePinPeriod(baseid);
                    int outdata =itema.optInt("materialValue");
                    int usersa = mpinsUserInfors.get(baseid);
                    updateAllowance(baseid, usersa + outdata);
                    float speeda = (float) 1.0;
                    String inforSpeeda = "";
                    if (mCheckWeighStatus) {
                        Log.d(TAG, "outData: mCheckWeighStatus=1=" + mCheckWeighStatus);
                        Log.d(TAG, "outData: moutmaterialsSpeedMap=2=" + moutmaterialsSpeedMap);

                        inforSpeeda = String.valueOf(SlovmeData.getSlovmeData().getTypea().getTypeid()) + "-" + String.valueOf(baseid) + "-" + String.valueOf(outdata);
                        Log.d(TAG, "outData: mCheckWeighStatus=2=" + inforSpeeda);

                        if (moutmaterialsSpeedMap.containsKey(inforSpeeda)) {
                            speeda = moutmaterialsSpeedMap.get(inforSpeeda);
                            float tempa1 = mPinsSpeeds.get(baseid);
                            double absDouble = Math.abs(tempa1 - speeda);
                            if (absDouble >= 15) {
                                speeda = tempa1;
                            }
                            Log.d(TAG, "outData: speeda=3=" + speeda);
                            if (speeda <= 0.5) {
                                speeda = mPinsSpeeds.get(baseid);
                                Log.d(TAG, "outData: speeda=4s=" + speeda);

                            }

                        } else {
                            speeda = mPinsSpeeds.get(baseid);
                            Log.d(TAG, "outData: speeda=4=" + speeda);

                        }

                    } else {
                        if (mCheckWeighNew) {
                            inforSpeeda = String.valueOf(SlovmeData.getSlovmeData().getTypea().getTypeid()) + "-" + String.valueOf(baseid) + "-" + String.valueOf(outdata);
                            Log.d(TAG, "outData: mCheckWeighStatus=2s=" + inforSpeeda);

                            if (moutmaterialsSpeedMap.containsKey(inforSpeeda)) {
                                speeda = moutmaterialsSpeedMap.get(inforSpeeda);
                                float tempa1 = mPinsSpeeds.get(baseid);
                                double absDouble = Math.abs(tempa1 - speeda);
                                if (absDouble >= 15) {
                                    speeda = tempa1;
                                }
                                Log.d(TAG, "outData: speeda=3s=" + speeda);
                                if (speeda <= 0.5) {
                                    speeda = mPinsSpeeds.get(baseid);
                                    Log.d(TAG, "outData: speeda=4s=" + speeda);

                                }
                            } else {
                                speeda = mPinsSpeeds.get(baseid);
                                Log.d(TAG, "outData: speeda=4s=" + speeda);

                            }
                        } else {
                            speeda = mPinsSpeeds.get(baseid);

                        }
                        Log.d(TAG, "outData: speeda=5=" + speeda);

                    }
                    float speedb = outdata * 1000 / speeda;
                    int timeas = (int) speedb;
                    MerilData merilData = mPinsMerilData.get(baseid);
                    //  timeas += Integer.parseInt(merilData.getCompensate());
                    if (!(mCheckWeighStatus || mCheckWeighNew)) {
                        timeas += Integer.parseInt(merilData.getCompensate());
                    }

                    if (timeas > timeAll) {
                        timeAll = timeas;
                    }

                    buffer[9 + nmbera + 7 * indexa] = (byte) getPinReal(baseid);//(byte) (tracks & 0xFF);
                    buffer[10 + nmbera + 7 * indexa] = (byte) Integer.parseInt(merilData.getMaterialDrit());

                    buffer[11 + nmbera + 7 * indexa] = (byte) Integer.parseInt(merilData.getMaterialCricle());
                    buffer[12 + nmbera + 7 * indexa] = (byte) Integer.parseInt(merilData.getMaterialCricle());

                    buffer[13 + nmbera + 7 * indexa] = (byte) ((timeas >> 16) & 0xFF);

                    buffer[14 + nmbera + 7 * indexa] = (byte) ((timeas >> 8) & 0xFF);

                    buffer[15 + nmbera + 7 * indexa] = (byte) ((timeas) & 0xFF);
                    index += 7;

                    indexa++;
                }
                buffer[8 + nmbera] = (byte) (7 * indexa);//(byte) ((tracks >> 8) & 0xFF);
                nmbera += 7 * indexa + 1;
                index += 1;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        Log.d(TAG, "outData--moutTeaMachineArrys=" + moutTeaMachineArrys.toString());

        lens = index;
        buffer[7] = (byte) lens;
        for (int i = 0; i <= 7 + index; i++) {

            tempb += buffer[i];
        }
        buffer[8 + index] = tempb;

        lena = 9 + index;
        String tempa = new String(buffer, 0, lena);
        String inforh = "";
        for (int i = 0; i < lena; i++) {

            String temp = Integer.toHexString(buffer[i] & 0xFF);
            if (temp.length() == 1) {
                temp = "0" + temp;
            }
            inforh = inforh + temp;
        }
        Log.d("findCurrentStatushssaa=", inforh);

        if (mSerialPort != null && moutTeaMachineArrys.size() <= 0) {
            mBuffStr = new byte[1024 * 3];
            m_AllLength = 0;
            mSerialPortUtils.sendByteSerialLenPort(buffer, 0, lena);

            return timeAll;
        }

        return timeAll;
    }

    //校验出料
    public void handPinTimes(int pinsa) {
        int outsa = 3000;
        int lens = 0;
        int lena = 0;
        int timeAll = 0;
        boolean isCricle = false;

        byte tempb = 0;
        byte[] buffer = new byte[1024];
        updatePinPeriod(pinsa);
        buffer[0] = 'W';
        buffer[1] = 'X';

        buffer[2] = 0x01;
        buffer[3] = (byte) m_frame_id;
        buffer[4] = 0x00;

        buffer[5] = 0x01;
        buffer[6] = 0x62;
        int index = 0;
        int nmbera = 0;
        int indexa = 0;

        int baseid = pinsa;
        int outdata = outsa;

        float speeda = mPinsSpeeds.get(baseid);
        //  float speedb = outdata * 1000 / speeda;
        int timeas = (int) outdata;
        MerilData merilData = mPinsMerilData.get(baseid);
        timeas += Integer.parseInt(merilData.getCompensate());
        buffer[9 + nmbera + 7 * indexa] = (byte) getPinReal(baseid);//(byte) (tracks & 0xFF);
        buffer[10 + nmbera + 7 * indexa] = (byte) Integer.parseInt(merilData.getMaterialDrit());

        buffer[11 + nmbera + 7 * indexa] = (byte) Integer.parseInt(merilData.getMaterialCricle());
        buffer[12 + nmbera + 7 * indexa] = (byte) Integer.parseInt(merilData.getMaterialCricle());

        buffer[13 + nmbera + 7 * indexa] = (byte) ((timeas >> 16) & 0xFF);

        buffer[14 + nmbera + 7 * indexa] = (byte) ((timeas >> 8) & 0xFF);

        buffer[15 + nmbera + 7 * indexa] = (byte) ((timeas) & 0xFF);
        timeAll += timeas;
        index += 7;
        buffer[8 + nmbera] = (byte) (7 * (indexa + 1));//(byte) ((tracks >> 8) & 0xFF);
        nmbera += 7 * (indexa + 1) + 1;
        index += 1;


        lens = index;
        buffer[7] = (byte) lens;
        for (int i = 0; i <= 7 + index; i++) {

            tempb += buffer[i];
        }
        buffer[8 + index] = tempb;

        lena = 9 + index;
        String tempa = new String(buffer, 0, lena);
        String inforh = "";
        for (int i = 0; i < lena; i++) {

            String temp = Integer.toHexString(buffer[i] & 0xFF);
            if (temp.length() == 1) {
                temp = "0" + temp;
            }
            inforh = inforh + temp;
        }
        Log.d("findCurrentStatushssaa=", inforh);

        if (mSerialPort != null) {
            mBuffStr = new byte[1024 * 3];
            mSerialPortUtils.sendByteSerialLenPort(buffer, 0, lena);

            return;
        }

        return;
    }

    //手动出料
    public int outHandlData(int pinsa, int outsa) {
        mIsCancels = false;
        int lens = 0;
        int lena = 0;
        int timeAll = 0;
        boolean isCricle = false;

        byte tempb = 0;
        byte[] buffer = new byte[1024];
        updatePinPeriod(pinsa);
        buffer[0] = 'W';
        buffer[1] = 'X';

        buffer[2] = 0x01;
        buffer[3] = (byte) m_frame_id;
        buffer[4] = 0x00;

        buffer[5] = 0x01;
        buffer[6] = 0x62;
        int index = 0;
        int nmbera = 0;
        int indexa = 0;

        int baseid = pinsa;
        int outdata = outsa;
        int usersa = mpinsUserInfors.get(baseid);
        updateAllowance(baseid, usersa + outdata);
        float speeda = mPinsSpeeds.get(baseid);
        float speedb = outdata * 1000 / speeda;
        int timeas = (int) speedb;
        MerilData merilData = mPinsMerilData.get(baseid);
        timeas += Integer.parseInt(merilData.getCompensate());
        buffer[9 + nmbera + 7 * indexa] = (byte) getPinReal(baseid);//(byte) (tracks & 0xFF);
        buffer[10 + nmbera + 7 * indexa] = (byte) Integer.parseInt(merilData.getMaterialDrit());

        buffer[11 + nmbera + 7 * indexa] = (byte) Integer.parseInt(merilData.getMaterialCricle());
        buffer[12 + nmbera + 7 * indexa] = (byte) Integer.parseInt(merilData.getMaterialCricle());

        buffer[13 + nmbera + 7 * indexa] = (byte) ((timeas >> 16) & 0xFF);

        buffer[14 + nmbera + 7 * indexa] = (byte) ((timeas >> 8) & 0xFF);

        buffer[15 + nmbera + 7 * indexa] = (byte) ((timeas) & 0xFF);
        timeAll += timeas;
        index += 7;
        buffer[8 + nmbera] = (byte) (7 * (indexa + 1));//(byte) ((tracks >> 8) & 0xFF);
        nmbera += 7 * (indexa + 1) + 1;
        index += 1;


        lens = index;
        buffer[7] = (byte) lens;
        for (int i = 0; i <= 7 + index; i++) {

            tempb += buffer[i];
        }
        buffer[8 + index] = tempb;

        lena = 9 + index;
        String tempa = new String(buffer, 0, lena);
        String inforh = "";
        for (int i = 0; i < lena; i++) {

            String temp = Integer.toHexString(buffer[i] & 0xFF);
            if (temp.length() == 1) {
                temp = "0" + temp;
            }
            inforh = inforh + temp;
        }
        Log.d("findCurrentStatushssaa=", inforh);

        if (mSerialPort != null) {
            mBuffStr = new byte[1024 * 3];
            mSerialPortUtils.sendByteSerialLenPort(buffer, 0, lena);

            return timeAll;
        }

        return timeAll;
    }

    //上料排空出料
    public int outUpData(HashMap<Integer, Integer> outlistsa) {
        int lens = 0;
        int lena = 0;
        int timeAll = 0;
        boolean isCricle = false;


        byte tempb = 0;
        byte[] buffer = new byte[1024];

        buffer[0] = 'W';
        buffer[1] = 'X';

        buffer[2] = 0x01;
        buffer[3] = (byte) m_frame_id;
        buffer[4] = 0x00;

        buffer[5] = 0x01;
        buffer[6] = 0x62;
        int index = 0;
        int nmbera = 0;
        int indexa = 0;

        // for (indexa = 0; indexa < arrycsall.length(); indexa++) {
        indexa = 0;
        for (Integer keyas : outlistsa.keySet()) {

            int baseid = keyas.intValue();
            int outdata = outlistsa.get(keyas);

            updatePinPeriod(baseid);
            int timeas = outdata;
            MerilData merilData = mPinsMerilData.get(baseid);

            if (timeas > timeAll) {
                timeAll = timeas;
            }

            buffer[9 + nmbera + 7 * indexa] = (byte) getPinReal(baseid);//(byte) (tracks & 0xFF);
            buffer[10 + nmbera + 7 * indexa] = (byte) Integer.parseInt(merilData.getMaterialDrit());

            buffer[11 + nmbera + 7 * indexa] = (byte) Integer.parseInt(merilData.getMaterialCricle());
            buffer[12 + nmbera + 7 * indexa] = (byte) Integer.parseInt(merilData.getMaterialCricle());

            buffer[13 + nmbera + 7 * indexa] = (byte) ((timeas >> 16) & 0xFF);

            buffer[14 + nmbera + 7 * indexa] = (byte) ((timeas >> 8) & 0xFF);

            buffer[15 + nmbera + 7 * indexa] = (byte) ((timeas) & 0xFF);
            index += 7;
            indexa++;
        }
        buffer[8 + nmbera] = (byte) (7 * indexa);//(byte) ((tracks >> 8) & 0xFF);
        nmbera += 7 * indexa + 1;
        index += 1;


        lens = index;
        buffer[7] = (byte) lens;
        for (int i = 0; i <= 7 + index; i++) {

            tempb += buffer[i];
        }
        buffer[8 + index] = tempb;

        lena = 9 + index;
        String tempa = new String(buffer, 0, lena);
        String inforh = "";
        for (int i = 0; i < lena; i++) {

            String temp = Integer.toHexString(buffer[i] & 0xFF);
            if (temp.length() == 1) {
                temp = "0" + temp;
            }
            inforh = inforh + temp;
        }
        Log.d("findCurrentStatushssaa=", inforh);

        if (mSerialPort != null) {

            mSerialPortUtils.sendByteSerialLenPort(buffer, 0, lena);

            return timeAll;
        }

        return timeAll;
    }

    //取消正常出料
    public void cancelWeighOut() {
        //  mTimeSalesTime.removeMessages(TIME_SALES_DELATE);
        // mTimeQmSalesTime.removeMessages(TIME_QM_SALES_DELATE);

        int lens = 0;
        int lena = 0;


        byte tempb = 0;
        byte[] buffer = new byte[1024];

        buffer[0] = 'W';
        buffer[1] = 'X';

        buffer[2] = 0x01;
        buffer[3] = (byte) m_frame_id;
        buffer[4] = 0x00;

        buffer[5] = 0x01;
        buffer[6] = 0x22;


        lens = 0;
        buffer[7] = (byte) lens;
        tempb = 0;
        for (int i = 0; i <= 7 + lens; i++) {

            tempb += buffer[i];
        }
        buffer[8 + lens] = tempb;

        lena = 9 + lens;
        String tempa = new String(buffer, 0, lena);
        String inforh = "";
        for (int i = 0; i < lena; i++) {

            String temp = Integer.toHexString(buffer[i] & 0xFF);
            if (temp.length() == 1) {
                temp = "0" + temp;
            }
            inforh = inforh + temp;
        }
        Log.d("handlPos=", inforh);

        if (mSerialPort != null) {
            mBuffStr = new byte[1024 * 3];
            mSerialPortUtils.sendByteSerialLenPort(buffer, 0, lena);

            return;
        }

        return;
    }
    public void cancelTempOut() {
        int lens = 0;
        int lena = 0;


        byte tempb = 0;
        byte[] buffer = new byte[1024];

        buffer[0] = 'W';
        buffer[1] = 'X';

        buffer[2] = 0x01;
        buffer[3] = (byte) m_frame_id;
        buffer[4] = 0x00;

        buffer[5] = 0x01;
        buffer[6] = 0x22;


        lens = 0;
        buffer[7] = (byte) lens;
        tempb = 0;
        for (int i = 0; i <= 7 + lens; i++) {

            tempb += buffer[i];
        }
        buffer[8 + lens] = tempb;

        lena = 9 + lens;
        String tempa = new String(buffer, 0, lena);
        String inforh = "";
        for (int i = 0; i < lena; i++) {

            String temp = Integer.toHexString(buffer[i] & 0xFF);
            if (temp.length() == 1) {
                temp = "0" + temp;
            }
            inforh = inforh + temp;
        }
        Log.d("handlPos=", inforh);

        if (mSerialPort != null) {
            mBuffStr = new byte[1024 * 3];
            mSerialPortUtils.sendByteSerialLenPort(buffer, 0, lena);

            return;
        }

        return;
    }
    //取消正常出料
    public void cancelOut() {
        mIsCancels = true;
        mTimeSalesTime.removeMessages(TIME_SALES_DELATE);
        mTimeQmSalesTime.removeMessages(TIME_QM_SALES_DELATE);
        mEmptyType = 0;
        int lens = 0;
        int lena = 0;


        byte tempb = 0;
        byte[] buffer = new byte[1024];

        buffer[0] = 'W';
        buffer[1] = 'X';

        buffer[2] = 0x01;
        buffer[3] = (byte) m_frame_id;
        buffer[4] = 0x00;

        buffer[5] = 0x01;
        buffer[6] = 0x22;


        lens = 0;
        buffer[7] = (byte) lens;
        tempb = 0;
        for (int i = 0; i <= 7 + lens; i++) {

            tempb += buffer[i];
        }
        buffer[8 + lens] = tempb;

        lena = 9 + lens;
        String tempa = new String(buffer, 0, lena);
        String inforh = "";
        for (int i = 0; i < lena; i++) {

            String temp = Integer.toHexString(buffer[i] & 0xFF);
            if (temp.length() == 1) {
                temp = "0" + temp;
            }
            inforh = inforh + temp;
        }
        Log.d("handlPos=", inforh);

        if (mSerialPort != null) {

            mBuffStr = new byte[1024 * 3];
             m_AllLength = 0;
            mSerialPortUtils.sendByteSerialLenPort(buffer, 0, lena);

            return;
        }

        return;
    }

    //称重校验
    public void upCheckLoadView(EditText check_input_edittext, CheckSetData checkSetData) {
        mIsCancels = false;
        mCurrentTypes = 0;
        mCurrentRunStatus = 0;
        mCurrentPins = checkSetData.getMenuid();
        mcheck_input_edittext = check_input_edittext;
        mcheckSetData = checkSetData;
        mWeiboDialog = WeiboDialogUtils.createLoadingDialog(mContext, mContext.getResources().getString(R.string.dialog_loading_texts));
        getWeight();
        mCheckedTime.sendEmptyMessageDelayed(TIME_CHECKED_BUTTON, 2000);


//        int[] writeData = new int[]{0x01, 0xFF};
//        byte[] bytess = ModbusUtils.getWriteModbus(deviceAddress, registerAddress, writeData);
//        String strs = ByteUtils.hexToStr(bytess);
//        System.out.println("写指令:"+strs);
    }

    public void getWeight() {
        int deviceAddress = 1;
        int registerAddress = 80;
        int registerCount = 2;

        byte[] bytes = ModbusUtils.getReadModbus(deviceAddress, registerAddress, registerCount);
        if (mSerialWeightPort != null) {
            //  StringBuffer coontentStringa = new StringBuffer();
            //  coontentStringa.append(bytes);
            //  mSerialPortWeightUtils.sendSerialPort(coontentStringa.toString() );
            mSerialPortWeightUtils.sendByteSerialPort(bytes);
        }

        String str = ByteUtils.hexToStr(bytes);
        System.out.println("读指令:" + str);
    }

    //更新速度
    public void updateSpeed(int pinsa, float speeds) {
        ContentValues values = new ContentValues();

        values.put("speed", speeds);


        mPinsSpeeds.put(pinsa, speeds);
        long insert = mBdwrite.update("speedcheacktb", values, "pin=? ", new String[]{(pinsa + "")});

    }

    //增加
    public void addAllowance(int pinsa, int allowance) {
        int allowanca = mpinsUserInfors.get(pinsa);
        allowanca -= allowance;
        if (allowanca <= 0) {
            allowanca = 0;
        }
        updateAllowance(pinsa, allowanca);
    }

    //更改用户用量
    public void updateAllowance(int pinsa, int allowance) {
        Log.d(TAG, "updateAllowance: pinsa=" + pinsa);
        Log.d(TAG, "updateAllowance: allowance=" + allowance);
        ContentValues values = new ContentValues();

        int allowances = allowance;
        Log.d(TAG, "updateAllowance: allowances=" + allowances);

        MerilData merilData = mPinsMerilData.get(pinsa);
        String materialFull = merilData.getMaterialFull();
        Log.d(TAG, "updateAllowance: materialFull=" + materialFull);

        int materialFulla = Integer.parseInt(materialFull);
        Log.d(TAG, "updateAllowance: materialFulla=" + materialFulla);

        if (allowances >= materialFulla) {
            allowances = materialFulla;
        }
        Log.d(TAG, "updateAllowance: allowances=" + allowances);

        values.put("surplus", allowances);


        mpinsUserInfors.put(pinsa, allowances);
        Log.d(TAG, "updateAllowance: mpinsUserInfors=" + mpinsUserInfors.toString());

        long insert = mBdwrite.update("capacitytb", values, "pin=? ", new String[]{(pinsa + "")});
        Log.d(TAG, "updateAllowance: insert=" + insert);

    }

    public void updateSetAllowance(int pinsa) {
        Log.d(TAG, "updateSetAllowance: pinsa=" + pinsa);

        MerilData merilData = mPinsMerilData.get(pinsa);
        String materialFull = merilData.getMaterialFull();
        int materialFulla = Integer.parseInt(materialFull);

        int allowanca = materialFulla;
        //  allowanca += allowanca;
        if (allowanca <= 0) {
            allowanca = 0;
        }

        Log.d(TAG, "updateSetAllowance: allowanca=" + allowanca);
        mpinsUserInfors.put(pinsa, allowanca);
        updateAllowance(pinsa, allowanca);
    }

    //物料更新界面
    public void allowanceViewUpdae() {
        mUserDataThread = new UserDataThread();
        mUserDataThread.start();
    }

    //更新质保期时间
    public void updatePinPeriod(int pinsa) {
        long timeGetTime = new Date().getTime() / 1000;

        int timeGetTimes = (int) (timeGetTime / 60);
        mMaterielQualitativeLen.put(pinsa, timeGetTimes);
    }

    //判断质保期是否过期
    public boolean juistPinPeriod(int pinsa) {
        boolean stausa = false;
        long timeGetTime = new Date().getTime() / 1000;

        int timeGetTimes = (int) (timeGetTime / 60);
        int tempa = mMaterielQualitativeLen.get(pinsa);
        MerilData merilData = mPinsMerilData.get(pinsa);
        int tempb = Integer.parseInt(merilData.getMaterialPerids());
        if ((tempa + tempb) <= timeGetTimes) {
            stausa = true;
        }
        return stausa;
    }

    //设置引脚对应的实际引脚
    public void setPinReal(int pinsa, int pinsb) {
        mPinsReala.put(pinsa, pinsb);
        ContentValues values = new ContentValues();
        values.put("reala", pinsb);
        long insert = mBdwrite.update("pininfor", values, "pin=? ", new String[]{(pinsa + "")});

        setParamView();
    }

    public void setParamView() {
        Toast.makeText(mContext, mContext.getResources().getString(R.string.home_page_set_param_success_text), Toast.LENGTH_SHORT).show();

    }

    //得到实际引脚
    public int getPinReal(int pinsa) {
        Integer pinsb = mPinsReala.get(pinsa);
        if (pinsb == null) {

            return pinsa;
        }
        if (pinsb == 0) {
            return pinsa;
        }
        return pinsb;
    }

    //销量
    //发送实时销量数据
    private void sendRequestRealTimeSalesData() {

        new Thread(new Runnable() {

            @Override
            public void run() {
                String strUrl = Urlinfor.getmUrlinfor().getInsertSalesvolume();
                Log.d(TAG, "sendRequestRealTimeSales strUrl=" + strUrl);
                URL url = null;
                try {
                    long currentTime = System.currentTimeMillis();
                    String timeNow = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(currentTime);
                    //    String ordernums = Urlinfor.getmUrlinfor().getMdevicenums() + String.valueOf(currentTime / 1000);
                    String ordernums = "";
                    if (DevicesInfors.getDevicesInfors().getDevice_type() != 2) {
                        ordernums = Urlinfor.getmUrlinfor().getMdevicenums() + String.valueOf(currentTime / 1000);
                    } else {
                        ordernums = CartDatas.getCartDatas().getmOrdernums();
                    }
                    Log.d(TAG, "sendRequestRealTimeSales ordernums=" + ordernums);
                    String salesvolumeOrderTime = timeNow;
                    Log.d(TAG, "sendRequestRealTimeSales salesvolumeOrderTime=" + salesvolumeOrderTime);
                    String secondMenuid = String.valueOf(SlovmeData.getSlovmeData().getRighta().getMenuId());
                    String cupTypeid = String.valueOf(SlovmeData.getSlovmeData().getTypea().getTypeid());
                    String contents = SlovmeData.getSlovmeData().getOutData().toString();
                    //   String timeNow = new SimpleDateFormat("yyyy-MM-dd").format(currentTime);
                    insertSalesouts(ordernums, salesvolumeOrderTime, secondMenuid, cupTypeid, contents);

                    url = new URL(strUrl);
                    HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
                    urlConn.setDoInput(true);
                    urlConn.setDoOutput(true);
                    urlConn.setRequestMethod("POST");
                    urlConn.setUseCaches(false);
                    //   urlConn.setRequestProperty("accept", "*/*");
                    urlConn.setRequestProperty("connection", "keep-alive");
                    // urlConn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

                    //   urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    urlConn.setRequestProperty("Content-Type", "application/json");
                    //     urlConn.setRequestProperty("Charset", "utf-8");
                     /*
                    if (urlConn instanceof HttpsURLConnection) {
                        try {
                            SSLContext sslContext = HttpsUtil.getSSLContextWithCer();

                            if (sslContext != null) {
                                SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
                                ((HttpsURLConnection) urlConn).setDefaultSSLSocketFactory(sslSocketFactory);

                            }
                        } catch (Exception e) {
                            e.printStackTrace();

                        }

                    }

                      */

                    urlConn.connect();


                    Log.d("aaaaa", "timeNow:==" + timeNow);
                    String postData = "";
                    try {

                        JSONObject json1 = new JSONObject();
                        json1.put("device_no", Urlinfor.getmUrlinfor().getMdevicenums());
                        json1.put("shop_id", Urlinfor.getmUrlinfor().getShopInformationId());
                        json1.put("cupTypeid", cupTypeid);
                        json1.put("secondMenuid", secondMenuid);
                        json1.put("salesvolumeOrderTime", salesvolumeOrderTime);
                        json1.put("ordernums", ordernums);
                        if (DevicesInfors.getDevicesInfors().getDevice_type() == 2) {
                            json1.put("pay_mode_code", CartDatas.getCartDatas().getPay_mode_code());
                        }
                        JSONArray arrya1 = new JSONArray();
                        JSONArray arrycsall = SlovmeData.getSlovmeData().getOutData();

                        for (int indexa = 0; indexa < arrycsall.length(); indexa++) {
                            JSONObject itema = arrycsall.getJSONObject(indexa);
                            JSONObject itrmeb = new JSONObject();

                            itrmeb.put("materialpines", itema.optString("materialpines"));
                            itrmeb.put("salesvolumeOutput", itema.optString("setbeverageOutput"));
                            arrya1.put(itrmeb);
                        }
                        json1.put("contents", arrya1);
                        postData = json1.toString();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    Log.d(TAG, "sendRequestRealTimeSales postData=" + postData);
                    //byte[] input = postData.getBytes("utf-8");
                    // byte[] postDataBytes = postData.getBytes(StandardCharsets.UTF_8);
                    PrintWriter dop = new PrintWriter(urlConn.getOutputStream());
                    dop.write(postData);

                    //  dop.write(input, 0, input.length);
                    dop.flush();
                    dop.close();


                    BufferedReader bufferReader = new BufferedReader(new InputStreamReader(urlConn.getInputStream(), "utf-8"));
                    String result = "";
                    String readline = null;
                    while ((readline = bufferReader.readLine()) != null) {
                        result += readline;
                    }
                    bufferReader.close();
                    urlConn.disconnect();

                    Log.d(TAG, "sendRequestRealTimeSales result=" + result);
                    if (result.length() <= 0) {
                        return;
                    }
                    try {
                        JSONObject resultJson = new JSONObject(result);
                        boolean status = resultJson.optBoolean("status");
                        if (status) {
                            String tordernums = resultJson.optString("ordernums");
                            deleteSalesouts(tordernums);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();

                    }

                } catch (IOException e) {

                    Log.d("aaaaa", "222=" + e.getMessage());

                    e.printStackTrace();
                }

            }
        }).start();//这个start()方法不要忘记了

    }

    private void sendRequestRealMqTimeSalesData() {

        new Thread(new Runnable() {

            @Override
            public void run() {
                String strUrl = Urlinfor.getmUrlinfor().getInsertSalesvolume();
                Log.d(TAG, "sendRequestRealTimeSales strUrl=" + strUrl);
                URL url = null;
                try {
                    /*
                     *
                     * */
                    long currentTime = System.currentTimeMillis();
                    String timeNow = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(currentTime);
                    String ordernums = SlovmeData.getSlovmeData().getOrderContentData().getmOrderNumber() + "-" + SlovmeData.getSlovmeData().getOrderContentData().getmContentName();
                    Log.d(TAG, "sendRequestRealMqTimeSalesData ordernums=" + ordernums);
                    String salesvolumeOrderTime = timeNow;
                    Log.d(TAG, "sendRequestRealMqTimeSalesData salesvolumeOrderTime=" + salesvolumeOrderTime);
                    String secondMenuid = String.valueOf(SlovmeData.getSlovmeData().getOrderContentData().getSecondMenuid());
                    String cupTypeid = String.valueOf(SlovmeData.getSlovmeData().getOrderContentData().getCupTypeids());
                    String contents = SlovmeData.getSlovmeData().getOutData().toString();
                    //   String timeNow = new SimpleDateFormat("yyyy-MM-dd").format(currentTime);
                    insertSalesouts(ordernums, salesvolumeOrderTime, secondMenuid, cupTypeid, contents);

                    url = new URL(strUrl);
                    HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
                    urlConn.setDoInput(true);
                    urlConn.setDoOutput(true);
                    urlConn.setRequestMethod("POST");
                    urlConn.setUseCaches(false);
                    //   urlConn.setRequestProperty("accept", "*/*");
                    urlConn.setRequestProperty("connection", "keep-alive");
                    // urlConn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

                    //   urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    urlConn.setRequestProperty("Content-Type", "application/json");
                    //     urlConn.setRequestProperty("Charset", "utf-8");
                    /*
                    if (urlConn instanceof HttpsURLConnection) {
                        try {
                            SSLContext sslContext = HttpsUtil.getSSLContextWithCer();

                            if (sslContext != null) {
                                SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
                                ((HttpsURLConnection) urlConn).setDefaultSSLSocketFactory(sslSocketFactory);

                            }
                        } catch (Exception e) {
                            e.printStackTrace();

                        }

                    }

                     */

                    urlConn.connect();


                    Log.d("aaaaa", "timeNow:==" + timeNow);
                    String postData = "";
                    try {

                        JSONObject json1 = new JSONObject();
                        json1.put("device_no", Urlinfor.getmUrlinfor().getMdevicenums());
                        json1.put("shop_id", Urlinfor.getmUrlinfor().getShopInformationId());
                        json1.put("cupTypeid", cupTypeid);
                        json1.put("secondMenuid", secondMenuid);
                        json1.put("salesvolumeOrderTime", salesvolumeOrderTime);
                        json1.put("ordernums", ordernums);
                        JSONArray arrya1 = new JSONArray();
                        JSONArray arrycsall = SlovmeData.getSlovmeData().getOutData();
                        Log.d(TAG, "runarrycsall==" + arrycsall);

                        for (int indexa = 0; indexa < arrycsall.length(); indexa++) {
                            JSONObject itema = arrycsall.getJSONObject(indexa);
                            JSONObject itrmeb = new JSONObject();

                            itrmeb.put("materialpines", itema.optString("materialpines"));
                            itrmeb.put("salesvolumeOutput", itema.optString("setbeverageOutput"));
                            arrya1.put(itrmeb);
                        }
                        json1.put("contents", arrya1);
                        postData = json1.toString();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    Log.d(TAG, "sendRequestRealMqTimeSalesData postData=" + postData);

                    //byte[] input = postData.getBytes("utf-8");
                    // byte[] postDataBytes = postData.getBytes(StandardCharsets.UTF_8);
                    PrintWriter dop = new PrintWriter(urlConn.getOutputStream());
                    dop.write(postData);

                    //  dop.write(input, 0, input.length);
                    dop.flush();
                    dop.close();


                    BufferedReader bufferReader = new BufferedReader(new InputStreamReader(urlConn.getInputStream(), "utf-8"));
                    String result = "";
                    String readline = null;
                    while ((readline = bufferReader.readLine()) != null) {
                        result += readline;
                    }
                    bufferReader.close();
                    urlConn.disconnect();

                    Log.d(TAG, "sendRequestRealMqTimeSalesData result=" + result);
                    if (result.length() <= 0) {
                        return;
                    }
                    try {
                        JSONObject resultJson = new JSONObject(result);
                        boolean status = resultJson.optBoolean("status");
                        if (status) {
                            String tordernums = resultJson.optString("ordernums");
                            deleteSalesouts(tordernums);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();

                    }

                } catch (IOException e) {

                    Log.d("aaaaa", "222=" + e.getMessage());

                    e.printStackTrace();
                }

            }
        }).start();//这个start()方法不要忘记了

    }

    private void insertSalesouts(String ordernums, String salesvolumeOrderTime, String secondMenuid, String cupTypeid, String contents) {
        Log.d("aaa", "insertSalesouts ordernums=" + ordernums);

        ContentValues values = new ContentValues();
        values.put("ordernums", ordernums);
        values.put("salesvolumeOrderTime", salesvolumeOrderTime);
        values.put("secondMenuid", secondMenuid);
        values.put("cupTypeid", cupTypeid);
        values.put("contents", contents);
        long insert = mBdwrite.insert("salesouts", null, values);

    }

    private boolean deleteSalesouts(String ordernums) {
        Log.d("aaa", "deleteSalesouts tordernums=" + ordernums);


        long staus = mBdwrite.delete("salesouts", "ordernums=?", new String[]{ordernums + ""});

        if (staus > 0) {
            return true;
        } else {
            return false;
        }
    }

    //清洗开始
    public void sendRequestRealClean() {


        new Thread(new Runnable() {

            @Override
            public void run() {
                String strUrl = Urlinfor.getmUrlinfor().getAddCleantime();
                URL url = null;
                try {
                    String beginTime = CleanRecordData.getCleanRecordData().getBeginTime();
                    String beginEnd = CleanRecordData.getCleanRecordData().getBeginEnd();
                    String realTime = CleanRecordData.getCleanRecordData().getRealTime();
                    String ordnumbers = CleanRecordData.getCleanRecordData().getOrdnumbers();
                    String cleantimename = CleanRecordData.getCleanRecordData().getCleantimename();
                    Log.d(TAG, "run: device_no==" + Urlinfor.getmUrlinfor().getMdevicenums());
                    Log.d(TAG, "run: cleantimeorderid==" + ordnumbers);
                    Log.d(TAG, "run: begin_time==" + beginTime);
                    Log.d(TAG, "run: theoretical_time==" + realTime);

                    Log.d(TAG, "run: cleantimename==" + URLEncoder.encode(cleantimename, "UTF-8"));
                    Log.d(TAG, "sendRequestEndRealClean-1: strUrl==" + strUrl);

                    Log.d(TAG, "sendRequestEndRealClean-1: device_no==" + Urlinfor.getmUrlinfor().getMdevicenums());
                    Log.d(TAG, "sendRequestEndRealClean-1: cleantimeorderid==" + ordnumbers);
                    Log.d(TAG, "sendRequestEndRealClean-1: begin_time==" + beginTime);
                    Log.d(TAG, "sendRequestEndRealClean-1: beginEnd==" + beginEnd);
                    Log.d(TAG, "sendRequestEndRealClean-1: theoretical_time==" + realTime);

                    insertCleartimea(ordnumbers, cleantimename, beginTime, realTime);


                    url = new URL(strUrl);
                    HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
                    urlConn.setDoInput(true);
                    urlConn.setDoOutput(true);
                    urlConn.setRequestMethod("POST");
                    urlConn.setUseCaches(false);
                    urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    urlConn.setRequestProperty("Charset", "utf-8");
                    /*
                    if (urlConn instanceof HttpsURLConnection) {
                        try {
                            SSLContext sslContext = HttpsUtil.getSSLContextWithCer();

                            if (sslContext != null) {
                                SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
                                ((HttpsURLConnection) urlConn).setDefaultSSLSocketFactory(sslSocketFactory);

                            }
                        } catch (Exception e) {
                            e.printStackTrace();

                        }

                    }

                     */
                    urlConn.connect();

                    //mdevicenums +
                    //   Log.d("aaaaa", "timeNow:==" + timeNow);
                    DataOutputStream dop = new DataOutputStream(urlConn.getOutputStream());
                    dop.writeBytes("device_no=" + Urlinfor.getmUrlinfor().getMdevicenums());
                    dop.writeBytes("&cleantimeorderid=" + ordnumbers);
                    dop.writeBytes("&cleantimename=" + URLEncoder.encode(cleantimename, "UTF-8"));
                    dop.writeBytes("&begin_time=" + beginTime);
                    dop.writeBytes("&theoretical_time=" + realTime);
                    dop.writeBytes("&cleantimeinfo=" + "");


                    dop.flush();
                    dop.close();


                    BufferedReader bufferReader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
                    String result = "";
                    String readline = null;
                    while ((readline = bufferReader.readLine()) != null) {
                        result += readline;
                    }
                    bufferReader.close();
                    urlConn.disconnect();

                    Log.d("aaa", "sendRequestClearOrderClientminqqss=" + result);
                    if (result.length() <= 0) {
                        return;
                    }
                    try {
                        JSONObject resultJson = new JSONObject(result);
                        boolean status = resultJson.optBoolean("status");
                        if (status) {
                            String cleantimeorderid = resultJson.optString("cleantimeorderid");

                            Log.d("aaa", "sendRequestClearOrderClientminqqss cleantimeorderid=" + cleantimeorderid);
                            deleteCleartimea(cleantimeorderid);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();

                    }


                } catch (IOException e) {

                    Log.d("aaaaa", "222=");

                    e.printStackTrace();
                }

            }
        }).start();//这个start()方法不要忘记了


    }

    public void insertCleartimea(String ordnumbers, String cleantimename, String beginTime, String realTime) {
        Log.d("aaa", "insertCleartimea ordernums=" + ordnumbers);

        ContentValues values = new ContentValues();
        values.put("ordernums", ordnumbers);
        values.put("cleantimename", cleantimename);
        values.put("begin_time", beginTime);
        values.put("theoretical_time", realTime);

        long insert = mBdwrite.insert("cleartimea", null, values);
    }

    public boolean deleteCleartimea(String ordnumbers) {
        Log.d("aaa", "deleteSalesouts tordernums=" + ordnumbers);


        long staus = mBdwrite.delete("cleartimea", "ordernums=?", new String[]{ordnumbers + ""});

        if (staus > 0) {
            return true;
        } else {
            return false;
        }
    }

    //清洗结束
    public void sendRequestEndRealClean() {

        mIsCancels = false;
        new Thread(new Runnable() {

            @Override
            public void run() {
                String strUrl = Urlinfor.getmUrlinfor().getSuperadditionCleantime();
                Log.d(TAG, "sendRequestEndRealClean: strUrl==" + strUrl);

                URL url = null;
                try {
                    String beginTime = CleanRecordData.getCleanRecordData().getBeginTime();
                    String beginEnd = CleanRecordData.getCleanRecordData().getBeginEnd();
                    String realTime = CleanRecordData.getCleanRecordData().getRealTime();
                    String ordnumbers = CleanRecordData.getCleanRecordData().getOrdnumbers();
                    String cleantimename = CleanRecordData.getCleanRecordData().getCleantimename();
                    Log.d(TAG, "sendRequestEndRealClean: device_no==" + Urlinfor.getmUrlinfor().getMdevicenums());
                    Log.d(TAG, "sendRequestEndRealClean: cleantimeorderid==" + ordnumbers);
                    Log.d(TAG, "sendRequestEndRealClean: begin_time==" + beginTime);
                    Log.d(TAG, "sendRequestEndRealClean: beginEnd==" + beginEnd);
                    Log.d(TAG, "sendRequestEndRealClean: theoretical_time==" + realTime);

                    Log.d(TAG, "sendRequestEndRealClean: cleantimename==" + URLEncoder.encode(cleantimename, "UTF-8"));

                    insertEndCleartimea(ordnumbers, cleantimename, beginTime, beginEnd, realTime);


                    url = new URL(strUrl);
                    HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
                    urlConn.setDoInput(true);
                    urlConn.setDoOutput(true);
                    urlConn.setRequestMethod("POST");
                    urlConn.setUseCaches(false);
                    urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    urlConn.setRequestProperty("Charset", "utf-8");
                     /*
                    if (urlConn instanceof HttpsURLConnection) {
                        try {
                            SSLContext sslContext = HttpsUtil.getSSLContextWithCer();

                            if (sslContext != null) {
                                SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
                                ((HttpsURLConnection) urlConn).setDefaultSSLSocketFactory(sslSocketFactory);

                            }
                        } catch (Exception e) {
                            e.printStackTrace();

                        }

                    }

                      */
                    urlConn.connect();

                    //mdevicenums +
                    //   Log.d("aaaaa", "timeNow:==" + timeNow);
                    DataOutputStream dop = new DataOutputStream(urlConn.getOutputStream());
                    dop.writeBytes("device_no=" + Urlinfor.getmUrlinfor().getMdevicenums());
                    dop.writeBytes("&cleantimeorderid=" + ordnumbers);
                    dop.writeBytes("&cleantimename=" + URLEncoder.encode(cleantimename, "UTF-8"));
                    dop.writeBytes("&begin_time=" + beginTime);
                    dop.writeBytes("&over_time=" + beginEnd);
                    dop.writeBytes("&theoretical_time=" + realTime);
                    dop.writeBytes("&cleantimeinfo=" + "");


                    dop.flush();
                    dop.close();


                    BufferedReader bufferReader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
                    String result = "";
                    String readline = null;
                    while ((readline = bufferReader.readLine()) != null) {
                        result += readline;
                    }
                    bufferReader.close();
                    urlConn.disconnect();

                    Log.d("aaa", "sendRequestEndRealClean=" + result);
                    if (result.length() <= 0) {
                        return;
                    }
                    try {
                        JSONObject resultJson = new JSONObject(result);
                        boolean status = resultJson.optBoolean("status");
                        if (status) {
                            String cleantimeorderid = resultJson.optString("cleantimeorderid");

                            // Log.d("aaa", "sendRequestEndRealClean cleantimeorderid=" + cleantimeorderid);
                            deleteEndCleartimea(cleantimeorderid);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();

                    }


                } catch (IOException e) {

                    Log.d("aaaaa", "222=");

                    e.printStackTrace();
                }

            }
        }).start();//这个start()方法不要忘记了


    }

    public void insertEndCleartimea(String ordnumbers, String cleantimename, String beginTime, String endTime, String realTime) {
        Log.d("aaa", "insertCleartimea ordernums=" + ordnumbers);

        ContentValues values = new ContentValues();
        values.put("ordernums", ordnumbers);
        values.put("cleantimename", cleantimename);
        values.put("begin_time", beginTime);
        values.put("over_time", endTime);
        values.put("theoretical_time", realTime);

        long insert = mBdwrite.insert("cleartimeb", null, values);
    }

    public boolean deleteEndCleartimea(String ordnumbers) {
        Log.d("aaa", "deleteSalesouts tordernums=" + ordnumbers);


        long staus = mBdwrite.delete("cleartimeb", "ordernums=?", new String[]{ordnumbers + ""});

        if (staus > 0) {
            return true;
        } else {
            return false;
        }
    }

    //处理销售记录
    private void handlSalesRecordData() {

        new Thread(new Runnable() {

            @Override
            public void run() {
                String strUrl = Urlinfor.getmUrlinfor().getInsertSalesvolume();
                Log.d(TAG, "handlSalesRecordData strUrl=" + strUrl);
                URL url = null;
                try {

                    String ordernums = "";
                    Log.d(TAG, "handlSalesRecordData ordernums=" + ordernums);
                    String salesvolumeOrderTime = "";
                    Log.d(TAG, "handlSalesRecordData salesvolumeOrderTime=" + salesvolumeOrderTime);
                    String secondMenuid = "";
                    String cupTypeid = "";
                    String contents = "";
                    Cursor cursor = null;


                    cursor = mBdread.rawQuery("select * from salesouts ", null);

                    if (cursor != null && cursor.getCount() > 0) {
                        while (cursor.moveToNext()) {

                            ordernums = cursor.getString(cursor.getColumnIndex("ordernums"));

                            salesvolumeOrderTime = cursor.getString(cursor.getColumnIndex("salesvolumeOrderTime"));
                            secondMenuid = cursor.getString(cursor.getColumnIndex("secondMenuid"));
                            cupTypeid = cursor.getString(cursor.getColumnIndex("cupTypeid"));

                            contents = cursor.getString(cursor.getColumnIndex("contents"));

                            break;
                        }
                    } else {
                        return;
                    }

                    url = new URL(strUrl);
                    HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
                    urlConn.setDoInput(true);
                    urlConn.setDoOutput(true);
                    urlConn.setRequestMethod("POST");
                    urlConn.setUseCaches(false);
                    //   urlConn.setRequestProperty("accept", "*/*");
                    urlConn.setRequestProperty("connection", "keep-alive");
                    // urlConn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

                    //   urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    urlConn.setRequestProperty("Content-Type", "application/json");
                    //     urlConn.setRequestProperty("Charset", "utf-8");
                     /*
                    if (urlConn instanceof HttpsURLConnection) {
                        try {
                            SSLContext sslContext = HttpsUtil.getSSLContextWithCer();

                            if (sslContext != null) {
                                SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
                                ((HttpsURLConnection) urlConn).setDefaultSSLSocketFactory(sslSocketFactory);

                            }
                        } catch (Exception e) {
                            e.printStackTrace();

                        }

                    }

                      */

                    urlConn.connect();


                    String postData = "";
                    try {

                        JSONObject json1 = new JSONObject();
                        json1.put("device_no", Urlinfor.getmUrlinfor().getMdevicenums());
                        json1.put("shop_id", Urlinfor.getmUrlinfor().getShopInformationId());
                        json1.put("cupTypeid", cupTypeid);
                        json1.put("secondMenuid", secondMenuid);
                        json1.put("salesvolumeOrderTime", salesvolumeOrderTime);
                        json1.put("ordernums", ordernums);
                        JSONArray arrya1 = new JSONArray();
                        JSONArray arrycsall = new JSONArray(contents);

                        for (int indexa = 0; indexa < arrycsall.length(); indexa++) {
                            JSONObject itema = arrycsall.getJSONObject(indexa);
                            JSONObject itrmeb = new JSONObject();

                            itrmeb.put("materialpines", itema.optString("materialpines"));
                            itrmeb.put("salesvolumeOutput", itema.optString("setbeverageOutput"));
                            arrya1.put(itrmeb);
                        }
                        json1.put("contents", arrya1);
                        postData = json1.toString();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    Log.d(TAG, "handlSalesRecordData postData=" + postData);
                    //byte[] input = postData.getBytes("utf-8");
                    // byte[] postDataBytes = postData.getBytes(StandardCharsets.UTF_8);
                    PrintWriter dop = new PrintWriter(urlConn.getOutputStream());
                    dop.write(postData);

                    //  dop.write(input, 0, input.length);
                    dop.flush();
                    dop.close();


                    BufferedReader bufferReader = new BufferedReader(new InputStreamReader(urlConn.getInputStream(), "utf-8"));
                    String result = "";
                    String readline = null;
                    while ((readline = bufferReader.readLine()) != null) {
                        result += readline;
                    }
                    bufferReader.close();
                    urlConn.disconnect();

                    Log.d(TAG, "handlSalesRecordData result=" + result);
                    if (result.length() <= 0) {
                        return;
                    }
                    try {
                        JSONObject resultJson = new JSONObject(result);
                        boolean status = resultJson.optBoolean("status");
                        if (status) {
                            String tordernums = resultJson.optString("ordernums");
                            deleteSalesouts(tordernums);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();

                    }

                } catch (IOException e) {

                    Log.d("aaaaa", "222=" + e.getMessage());

                    e.printStackTrace();
                }

            }
        }).start();//这个start()方法不要忘记了


        mSaleRecordSysncHandler.sendEmptyMessageDelayed(2, mSaleRecordSysncTime);
    }

    //处理清洗记录
    private void handlClearRecordData() {


        new Thread(new Runnable() {

            @Override
            public void run() {
                String strUrl = Urlinfor.getmUrlinfor().getAddCleantime();
                URL url = null;
                try {
                    String beginTime = "";
                    ;
                    String beginEnd = "";
                    String realTime = "";
                    String ordnumbers = "";
                    String cleantimename = "";

                    Cursor cursor = null;


                    cursor = mBdread.rawQuery("select * from cleartimea ", null);

                    if (cursor != null && cursor.getCount() > 0) {
                        while (cursor.moveToNext()) {

                            ordnumbers = cursor.getString(cursor.getColumnIndex("ordernums"));

                            cleantimename = cursor.getString(cursor.getColumnIndex("cleantimename"));
                            beginTime = cursor.getString(cursor.getColumnIndex("begin_time"));
                            realTime = cursor.getString(cursor.getColumnIndex("theoretical_time"));


                            break;
                        }
                    } else {
                        return;
                    }


                    Log.d(TAG, "handlClearRecordData1: device_no==" + Urlinfor.getmUrlinfor().getMdevicenums());
                    Log.d(TAG, "handlClearRecordData1: cleantimeorderid==" + ordnumbers);
                    Log.d(TAG, "handlClearRecordData1: begin_time==" + beginTime);
                    Log.d(TAG, "handlClearRecordData1: theoretical_time==" + realTime);

                    Log.d(TAG, "handlClearRecordData1: cleantimename==" + URLEncoder.encode(cleantimename, "UTF-8"));


                    url = new URL(strUrl);
                    HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
                    urlConn.setDoInput(true);
                    urlConn.setDoOutput(true);
                    urlConn.setRequestMethod("POST");
                    urlConn.setUseCaches(false);
                    urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    urlConn.setRequestProperty("Charset", "utf-8");
                    /*
                    if (urlConn instanceof HttpsURLConnection) {
                        try {
                            SSLContext sslContext = HttpsUtil.getSSLContextWithCer();

                            if (sslContext != null) {
                                SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
                                ((HttpsURLConnection) urlConn).setDefaultSSLSocketFactory(sslSocketFactory);

                            }
                        } catch (Exception e) {
                            e.printStackTrace();

                        }

                    }

                     */
                    urlConn.connect();

                    //mdevicenums +
                    //   Log.d("aaaaa", "timeNow:==" + timeNow);
                    DataOutputStream dop = new DataOutputStream(urlConn.getOutputStream());
                    dop.writeBytes("device_no=" + Urlinfor.getmUrlinfor().getMdevicenums());
                    dop.writeBytes("&cleantimeorderid=" + ordnumbers);
                    dop.writeBytes("&cleantimename=" + URLEncoder.encode(cleantimename, "UTF-8"));
                    dop.writeBytes("&begin_time=" + beginTime);
                    dop.writeBytes("&theoretical_time=" + realTime);
                    dop.writeBytes("&cleantimeinfo=" + "");


                    dop.flush();
                    dop.close();


                    BufferedReader bufferReader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
                    String result = "";
                    String readline = null;
                    while ((readline = bufferReader.readLine()) != null) {
                        result += readline;
                    }
                    bufferReader.close();
                    urlConn.disconnect();

                    Log.d("aaa", "handlClearRecordData1=" + result);
                    if (result.length() <= 0) {
                        return;
                    }
                    try {
                        JSONObject resultJson = new JSONObject(result);
                        boolean status = resultJson.optBoolean("status");
                        if (status) {
                            String cleantimeorderid = resultJson.optString("cleantimeorderid");

                            Log.d("aaa", "handlClearRecordData1 cleantimeorderid=" + cleantimeorderid);
                            deleteCleartimea(cleantimeorderid);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();

                    }


                } catch (IOException e) {

                    Log.d("aaaaa", "222=");

                    e.printStackTrace();
                }

            }
        }).start();//这个start()方法不要忘记了


        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                String strUrl = Urlinfor.getmUrlinfor().getSuperadditionCleantime();
                Log.d(TAG, "handlClearRecordData: strUrl==" + strUrl);

                URL url = null;
                try {
                    String beginTime = "";
                    String beginEnd = "";
                    String realTime = "";
                    String ordnumbers = "";
                    String cleantimename = "";
                    Cursor cursor = null;


                    cursor = mBdread.rawQuery("select * from cleartimeb ", null);

                    if (cursor != null && cursor.getCount() > 0) {
                        while (cursor.moveToNext()) {

                            ordnumbers = cursor.getString(cursor.getColumnIndex("ordernums"));

                            cleantimename = cursor.getString(cursor.getColumnIndex("cleantimename"));
                            beginTime = cursor.getString(cursor.getColumnIndex("begin_time"));
                            realTime = cursor.getString(cursor.getColumnIndex("theoretical_time"));
                            beginEnd = cursor.getString(cursor.getColumnIndex("over_time"));


                            break;
                        }
                    } else {
                        return;
                    }
                    Log.d(TAG, "handlClearRecordData: device_no==" + Urlinfor.getmUrlinfor().getMdevicenums());
                    Log.d(TAG, "handlClearRecordData: cleantimeorderid==" + ordnumbers);
                    Log.d(TAG, "handlClearRecordData: begin_time==" + beginTime);
                    Log.d(TAG, "handlClearRecordData: theoretical_time==" + realTime);

                    Log.d(TAG, "handlClearRecordData: cleantimename==" + URLEncoder.encode(cleantimename, "UTF-8"));


                    url = new URL(strUrl);
                    HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
                    urlConn.setDoInput(true);
                    urlConn.setDoOutput(true);
                    urlConn.setRequestMethod("POST");
                    urlConn.setUseCaches(false);
                    urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    urlConn.setRequestProperty("Charset", "utf-8");
                    /*
                    if (urlConn instanceof HttpsURLConnection) {
                        try {
                            SSLContext sslContext = HttpsUtil.getSSLContextWithCer();

                            if (sslContext != null) {
                                SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
                                ((HttpsURLConnection) urlConn).setDefaultSSLSocketFactory(sslSocketFactory);

                            }
                        } catch (Exception e) {
                            e.printStackTrace();

                        }

                    }

                     */
                    urlConn.connect();

                    //mdevicenums +
                    //   Log.d("aaaaa", "timeNow:==" + timeNow);
                    DataOutputStream dop = new DataOutputStream(urlConn.getOutputStream());
                    dop.writeBytes("device_no=" + Urlinfor.getmUrlinfor().getMdevicenums());
                    dop.writeBytes("&cleantimeorderid=" + ordnumbers);
                    dop.writeBytes("&cleantimename=" + URLEncoder.encode(cleantimename, "UTF-8"));
                    dop.writeBytes("&begin_time=" + beginTime);
                    dop.writeBytes("&over_time=" + beginEnd);
                    dop.writeBytes("&theoretical_time=" + realTime);
                    dop.writeBytes("&cleantimeinfo=" + "");


                    dop.flush();
                    dop.close();


                    BufferedReader bufferReader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
                    String result = "";
                    String readline = null;
                    while ((readline = bufferReader.readLine()) != null) {
                        result += readline;
                    }
                    bufferReader.close();
                    urlConn.disconnect();

                    Log.d("aaa", "handlClearRecordData=" + result);
                    if (result.length() <= 0) {
                        return;
                    }
                    try {
                        JSONObject resultJson = new JSONObject(result);
                        boolean status = resultJson.optBoolean("status");
                        if (status) {
                            String cleantimeorderid = resultJson.optString("cleantimeorderid");

                            // Log.d("aaa", "handlClearRecordData cleantimeorderid=" + cleantimeorderid);
                            deleteEndCleartimea(cleantimeorderid);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();

                    }


                } catch (IOException e) {

                    Log.d("aaaaa", "222=");

                    e.printStackTrace();
                }

            }
        }).start();//这个start()方法不要忘记了


        mClearRecordSysncHandler.sendEmptyMessageDelayed(3, mClearRecordSysncTime);

    }

    //处理发送来的指令
    public void handlCmdMqttData(String cmds) {
        try {

            Log.d(TAG, "handlCmdMqttData=cmds=" + cmds);

            JSONObject jsona = new JSONObject(cmds);
            if (jsona.has("cmd")) {
                String cmda = jsona.optString("cmd");
                if (cmda.equals("close")) {
                    if (home_gae_error_rlativeLayout != null) {
                        String errors = mContext.getResources().getString(R.string.main_local_device_error_two);
                        home_gae_error_rlativeLayout.setVisibility(RelativeLayout.VISIBLE);

                        mtxtErrorTip.setText(mContext.getResources().getString(R.string.main_local_device_two) + errors);
                        // mtxtErrorTip.setVisibility(TextView.VISIBLE);
                        // return;
                    }
                }
                if (cmda.equals("open")) {
                    if (home_gae_error_rlativeLayout != null) {
                        home_gae_error_rlativeLayout.setVisibility(RelativeLayout.GONE);

                    }
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();


        }
    }

    //处理店面发送来的数据
    public void handlMqttData(String cmds) {
        try {

            Log.d(TAG, "handlMqttData=cmds=" + cmds);

            JSONObject jsona = new JSONObject(cmds);

            if (jsona.has("cmd") && jsona.has("infor")) {
                String cmda = jsona.optString("cmd");
                JSONArray infor = jsona.optJSONArray("infor");
                String infors = ContentInfor.getmUrlinfor().getInforMenus();


                if (cmda.equals("add")) {
                    JSONArray jsonArrya = new JSONArray(infors);

                    for (int i = 0; i < jsonArrya.length(); i++) {
                        JSONObject aitema = jsonArrya.getJSONObject(i);
                        String firstMenuid = aitema.opt("firstMenuid").toString();
                        String firstMenuNames = aitema.opt("firstMenuNames").toString();
                        JSONArray secondMenu = aitema.optJSONArray("children");

                        for (int j = 0; j < secondMenu.length(); j++) {
                            JSONObject itema = secondMenu.getJSONObject(j);

                            String secondMenuid = itema.opt("secondMenuid").toString();
                            String secondMenuNames = itema.opt("secondMenuNames").toString();
                            String secondMenuReserve = itema.opt("secondMenuReserve").toString();
                            JSONArray childrenb = itema.optJSONArray("children");
                            for (int k = 0; k < childrenb.length(); k++) {
                                JSONObject atm = childrenb.getJSONObject(k);
                                Log.d(TAG, "handlMqttData: atm==" + atm.toString());
                                Log.d(TAG, "handlMqttData: Urlinfor.getmUrlinfor().getShopInformationNo()==" + Urlinfor.getmUrlinfor().getShopInformationNo());


                                int typeid = atm.optInt("cupTypeid");
                                String typename = atm.optString("cupTypeNames");
                                String errorData = "0";
                                if (atm.has("errorData")) {
                                    errorData = atm.optString("errorData");
                                }
                                String typeinfor = atm.optString("cupTypeReserve");
                                String cupTypeReserve2 = atm.optString("cupTypeReserve2");
                                String productCode = atm.optString("productCode");
                                for (int m = 0; m < infor.length(); m++) {
                                    JSONObject atmb = infor.getJSONObject(m);
                                    Log.d(TAG, "handlMqttData: atmb==" + atmb.toString());
                                    String orderId = atmb.optString("orderId");
                                    String orderTime = atmb.optString("orderTime");
                                    String shopCode = atmb.optString("shopCode");
                                    String cupNum = atmb.optString("cupNum");
                                    Log.d(TAG, "handlMqttData: shopCode==" + shopCode);

                                    String productCodea = atmb.optString("productCode");
                                    if (productCode.equals(productCodea) && shopCode.equals(Urlinfor.getmUrlinfor().getShopInformationNo())) {
                                        JSONArray content = atm.optJSONArray("children");

                                        if (fg2 != null) {

                                            String contentName = cupNum;
                                            String orderNumber = orderId;

                                            String firstName = firstMenuid;
                                            String secondName = secondMenuNames;
                                            String cupType = typename;
                                            String beverageNameTag = cupTypeReserve2;
                                            String orderDetail = content.toString();
                                            String cupTypeids = String.valueOf(typeid);

                                            fg2.addItem(new OrderContentData(contentName,
                                                    orderNumber, orderTime, firstName,
                                                    secondName, cupType, beverageNameTag,
                                                    orderDetail, firstMenuid, secondMenuid,
                                                    cupTypeids, secondMenuReserve, "", errorData));


                                        }

                                    }
                                }


                            }
                        }
                    }

                }
                if (cmda.equals("del")) {
                    JSONArray infora = jsona.optJSONArray("infor");
                    for (int i = 0; i < infora.length(); i++) {
                        JSONObject atmb = infora.getJSONObject(i);
                        String orderId = atmb.optString("orderId");
                        String cupNum = atmb.optString("cupNum");
                        if (fg2 != null) {
                            for (int j = 0; j < fg2.getItemLength(); j++) {
                                OrderContentData orderContentData = fg2.getItemInfor(j);
                                if (orderContentData != null && orderContentData.getmContentName().equals(orderId) && Integer.parseInt(cupNum) == Integer.parseInt(orderContentData.getmImgPath())) {
                                    fg2.removeOrderContentData(orderContentData);
                                }
                            }
                        }
                    }
                }

            }
        } catch (JSONException e) {
            e.printStackTrace();


        }
    }

    //更新物联网
    public void updateMqSales() {

        new Thread(new Runnable() {

            @Override
            public void run() {
                String strUrl = Urlinfor.getmUrlinfor().getUpdateSalesvolume();
                URL url = null;
                try {
                    String cupNum = "";


                    String ordnumbers = "";


                    OrderContentData orderContentData = SlovmeData.getSlovmeData().getOrderContentData();

                    ordnumbers = orderContentData.getmContentName();
                    cupNum = orderContentData.getmImgPath();

                    Log.d(TAG, "handlClearRecordData1: device_no==" + Urlinfor.getmUrlinfor().getMdevicenums());
                    Log.d(TAG, "handlClearRecordData1: cleantimeorderid==" + ordnumbers);


                    url = new URL(strUrl);
                    HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
                    urlConn.setDoInput(true);
                    urlConn.setDoOutput(true);
                    urlConn.setRequestMethod("POST");
                    urlConn.setUseCaches(false);
                    urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    urlConn.setRequestProperty("Charset", "utf-8");
                    /*
                    if (urlConn instanceof HttpsURLConnection) {
                        try {
                            SSLContext sslContext = HttpsUtil.getSSLContextWithCer();

                            if (sslContext != null) {
                                SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
                                ((HttpsURLConnection) urlConn).setDefaultSSLSocketFactory(sslSocketFactory);

                            }
                        } catch (Exception e) {
                            e.printStackTrace();

                        }

                    }

                     */
                    urlConn.connect();

                    //mdevicenums +
                    //   Log.d("aaaaa", "timeNow:==" + timeNow);
                    DataOutputStream dop = new DataOutputStream(urlConn.getOutputStream());
                    dop.writeBytes("device_no=" + Urlinfor.getmUrlinfor().getMdevicenums());
                    dop.writeBytes("&orderNumbers=" + ordnumbers);
                    dop.writeBytes("&cupNumbers=" + cupNum);
                    dop.writeBytes("&shopCode=" + Urlinfor.getmUrlinfor().getShopInformationNo());


                    dop.flush();
                    dop.close();


                    BufferedReader bufferReader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
                    String result = "";
                    String readline = null;
                    while ((readline = bufferReader.readLine()) != null) {
                        result += readline;
                    }
                    bufferReader.close();
                    urlConn.disconnect();

                    Log.d("aaa", "handlClearRecordData1=" + result);
                    if (result.length() <= 0) {
                        return;
                    }
                    try {
                        JSONObject resultJson = new JSONObject(result);
                        boolean status = resultJson.optBoolean("status");
                        if (status) {
                            String cleantimeorderid = resultJson.optString("cleantimeorderid");

                            Log.d("aaa", "handlClearRecordData1 cleantimeorderid=" + cleantimeorderid);
                            deleteCleartimea(cleantimeorderid);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();

                    }


                } catch (IOException e) {

                    Log.d("aaaaa", "222=");

                    e.printStackTrace();
                }

            }
        }).start();//这个start()方法不要忘记了

    }

    //取消物联网
    public void cancelMqSales() {

        new Thread(new Runnable() {

            @Override
            public void run() {
                String strUrl = Urlinfor.getmUrlinfor().getCancelSalesvolume();
                URL url = null;
                try {
                    String cupNum = "";


                    String ordnumbers = "";


                    OrderContentData orderContentData = SlovmeData.getSlovmeData().getOrderContentData();

                    ordnumbers = orderContentData.getmContentName();
                    ;//orderContentData.getmOrderNumber();
                    cupNum = orderContentData.getmImgPath();

                    Log.d(TAG, "cancelMqSales: device_no==" + Urlinfor.getmUrlinfor().getMdevicenums());
                    Log.d(TAG, "cancelMqSales: cleantimeorderid==" + ordnumbers);


                    url = new URL(strUrl);
                    HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
                    urlConn.setDoInput(true);
                    urlConn.setDoOutput(true);
                    urlConn.setRequestMethod("POST");
                    urlConn.setUseCaches(false);
                    urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    urlConn.setRequestProperty("Charset", "utf-8");
                    /*
                    if (urlConn instanceof HttpsURLConnection) {
                        try {
                            SSLContext sslContext = HttpsUtil.getSSLContextWithCer();

                            if (sslContext != null) {
                                SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
                                ((HttpsURLConnection) urlConn).setDefaultSSLSocketFactory(sslSocketFactory);

                            }
                        } catch (Exception e) {
                            e.printStackTrace();

                        }

                    }

                     */
                    urlConn.connect();

                    //mdevicenums +
                    //   Log.d("aaaaa", "timeNow:==" + timeNow);
                    DataOutputStream dop = new DataOutputStream(urlConn.getOutputStream());
                    dop.writeBytes("device_no=" + Urlinfor.getmUrlinfor().getMdevicenums());
                    dop.writeBytes("&orderNumbers=" + ordnumbers);
                    dop.writeBytes("&cupNumbers=" + cupNum);
                    dop.writeBytes("&shopCode=" + Urlinfor.getmUrlinfor().getShopInformationNo());


                    dop.flush();
                    dop.close();


                    BufferedReader bufferReader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
                    String result = "";
                    String readline = null;
                    while ((readline = bufferReader.readLine()) != null) {
                        result += readline;
                    }
                    bufferReader.close();
                    urlConn.disconnect();

                    Log.d("aaa", "cancelMqSales=" + result);
                    if (result.length() <= 0) {
                        return;
                    }
                    try {
                        JSONObject resultJson = new JSONObject(result);
                        boolean status = resultJson.optBoolean("status");
                        if (status) {
                            String cleantimeorderid = resultJson.optString("cleantimeorderid");

                            Log.d("aaa", "cancelMqSales cleantimeorderid=" + cleantimeorderid);
                            deleteCleartimea(cleantimeorderid);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();

                    }


                } catch (IOException e) {

                    Log.d("aaaaa", "222=");

                    e.printStackTrace();
                }

            }
        }).start();//这个start()方法不要忘记了

    }

    //处理扫描图片
    public void handlScanInfor(String trcts) {
        mIsCancels = false;
        String infors = ContentInfor.getmUrlinfor().getInforMenus();
//
//        if (true) {
//            Toast.makeText(mContext, trcts, Toast.LENGTH_SHORT).show();
//
//        }
        if (trcts.contains(",")) {
            String[] lista = trcts.split(",");
            String oreders = "";
            String cupnuma = "";
            boolean isFind = false;
            if (lista.length >= 2) {
                oreders = lista[0];
                cupnuma = lista[1];
            }
            if (fg2 != null) {
                for (int j = 0; j < fg2.getItemLength(); j++) {
                    OrderContentData orderContentData = fg2.getItemInfor(j);
                    //Toast.makeText(mContext, "aaa="+orderContentData.getmOrderNumber().toString() +"="+orderContentData.getmContentName().toString(), Toast.LENGTH_SHORT).show();

                    if (orderContentData != null && orderContentData.getmContentName().equals(oreders) && Integer.parseInt(cupnuma) == Integer.parseInt(orderContentData.getmImgPath())) {

                        //  if (orderContentData != null && orderContentData.getmContentName().equals(oreders) && Integer.parseInt(cupnuma) == Integer.parseInt(orderContentData.getmImgPath())) {

                        if (mScancodePopupView == null) {
                            mScancodePopupView = new ScancodePopupView(mContext);
                        }

                        mScancodePopupView.show();
                        mScancodePopupView.setNameInfor(orderContentData.getSecondName());
                        mScancodePopupView.setRunTime(orderContentData.getCupType());
                        mScancodePopupView.setTypes(2);
                        mScancodePopupView.setLeft(null);
                        mScancodePopupView.setRight(null);
                        mScancodePopupView.setSpecifData(null);
                        mScancodePopupView.setOrderContentData(orderContentData);
                        isFind = true;
                        break;
                    }
                }
            }
            if (!isFind) {
                Toast.makeText(mContext, mContext.getResources().getString(R.string.home_page_find_param_error_one_text), Toast.LENGTH_SHORT).show();

            }
        } else {
            boolean isFind = false;
            // HomePages.mHomePages.setSpecifPopuView(itemb,itema,itema.getMenuNames(),itema.getContents());
            //if(trcts.contains("\"")){ ?o=20052682242507090001&equ=yxzbc07
            boolean isTops = false;
            String trcta = trcts.replace("\"", "");
            if (trcta.contains("equ=")) {
                String trctb = trcta;
                String[] trlistb = trctb.split("equ=");
                if (trlistb.length >= 2) {
                    String trctc = trlistb[1];
                    trcta = trctc;
                    isTops = true;
                }
            }

            try {
                JSONArray jsonArrya = new JSONArray(infors);

                for (int i = 0; i < jsonArrya.length(); i++) {
                    JSONObject aitema = jsonArrya.getJSONObject(i);
                    if( aitema.isNull("produceType") || aitema.isNull("produceTypeName") || aitema.isNull("produceList") ){
                        continue;
                    }
                    String firstMenuid =  String.valueOf( aitema.optLong("produceType") );
                    String firstMenuNames = aitema.opt("produceTypeName").toString();
                    JSONArray secondMenu = aitema.optJSONArray("produceList");

                    for (int j = 0; j < secondMenu.length(); j++) {
                        JSONObject itema = secondMenu.getJSONObject(j);
                        if( itema.isNull("id") || itema.isNull("name") || itema.isNull("produceSpecificationList")|| itema.isNull("produceSpecificationGroupList") ){
                            continue;
                        }
                        String secondMenuid = String.valueOf( aitema.optLong("id") );
                        String secondMenuNames =  itema.opt("name").toString();
                        String secondMenuReserve = "";
                        JSONArray childrenb = itema.optJSONArray("produceSpecificationList");
                        JSONArray produceSpecificationGroupList = itema.optJSONArray("produceSpecificationGroupList");
                        for (int k = 0; k < childrenb.length(); k++) {
                            JSONObject atm = childrenb.getJSONObject(k);


                            Log.d(TAG, "handlMqttData: atm==" + atm.toString());
                            Log.d(TAG, "handlMqttData: Urlinfor.getmUrlinfor().getShopInformationNo()==" + Urlinfor.getmUrlinfor().getShopInformationNo());


                            int typeid = atm.optInt("cupTypeid");
                            String typename = atm.optString("cupTypeNames");
                            String typeinfor = atm.optString("cupTypeReserve");
                            String cupTypeReserve2 = atm.optString("cupTypeReserve2");
                            String productCode = atm.optString("productCode");

                            Log.d(TAG, "handlMqttData: productCode==" + productCode);
                            Log.d(TAG, "handlMqttData: trcta==" + trcta);

                            if (trcta.length() > 0 && productCode.length() > 0 && productCode.equals(trcta)) {
                                JSONArray content = atm.optJSONArray("children");
                                Log.d(TAG, "handlMqttData: content==" + content);


                                HomepageLeftMenuItemData lefta = new HomepageLeftMenuItemData(Integer.parseInt(firstMenuid), firstMenuNames, secondMenu.toString());
                                HomepageGridRightMenuItemData righta = new HomepageGridRightMenuItemData(Integer.parseInt(secondMenuid), secondMenuNames, childrenb.toString() ,produceSpecificationGroupList.toString());
                                SpecifData specifData = new SpecifData(typeid, typename, typeinfor, cupTypeReserve2, productCode, content.toString());
                                if (isTops) {
                                    SlovmeData.getSlovmeData().setLefta(lefta);
                                    SlovmeData.getSlovmeData().setRighta(righta);
                                    HomePages.mHomePages.setProduceProgress(specifData,righta.getMenuNames()+"-"+specifData.getTypename(),specifData.getTypeOrder() ,specifData.getContent());

                                    isFind = true;
                                    break;
                                }

                                if (mScancodePopupView == null) {
                                    mScancodePopupView = new ScancodePopupView(mContext);
                                }

                                mScancodePopupView.show();
                                mScancodePopupView.setNameInfor(righta.getMenuNames());
                                mScancodePopupView.setRunTime(typename);
                                mScancodePopupView.setTypes(1);
                                mScancodePopupView.setLeft(lefta);
                                mScancodePopupView.setRight(righta);
                                mScancodePopupView.setSpecifData(specifData);
                                mScancodePopupView.setOrderContentData(null);
                                isFind = true;
                                break;
                            }


                        }
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();


            }
            //}


            if (!isFind) {
                Toast.makeText(mContext, mContext.getResources().getString(R.string.home_page_find_param_error_one_text), Toast.LENGTH_SHORT).show();

            }
        }

        mCurrentisScan = true;
    }

    //余量处理
    class UserDataThread extends Thread {
        @Override
        public void run() {

            for (int i = 0; i < mHomepageMertrielProgressItemData.size(); i++) {
                HomepageMertrielProgressItemData itma = (HomepageMertrielProgressItemData) mHomepageMertrielProgressItemData.get(i);
                int ids = itma.getId();
                Integer users = mpinsUserInfors.get(ids);
                Log.d(TAG, "run: ids=" + ids);
                Log.d(TAG, "run: users=" + users);
                if (users != null) {
                    itma.setUseMmaterial(users);
                }
            }
            Message msg = new Message();
            msg.what = 1;  //消息(一个整型值)
            mTimeShowHandler.sendMessage(msg);
        }
    }

    //物联网
    class HandlDataThread extends Thread {
        @Override
        public void run() {
            initRequestSourceData();
            mqtt_handl();
        }
    }

    class HandlSendThread extends Thread {
        @Override
        public void run() {

            while (true) {
                String infors = "";
                try {
                    JSONArray aary1 = new JSONArray();
                    for (int keys : mpinsUserInfors.keySet()) {

                        if (keys > 0) {

                            JSONObject jso1 = new JSONObject();
                            Log.d(TAG, "HandlSendThread: keys=" + keys);
                            Log.d(TAG, "HandlSendThread: mpinsUserInfors.get(keys)=" + mpinsUserInfors.get(keys));
                            MerilData merilData = mPinsMerilData.get(keys);


                            int materialFull = 100;
                            if (merilData != null) {
                                materialFull = Integer.parseInt(merilData.getMaterialFull());
                            }
                            jso1.put("materialpins", String.valueOf(keys));
                            jso1.put("dosage", String.valueOf(mpinsUserInfors.get(keys)));
                            jso1.put("allowance", String.valueOf(materialFull - mpinsUserInfors.get(keys)));


                            aary1.put(jso1);
                        }
                    }
                    infors = aary1.toString();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                try {
                    //topic = client.getTopic(myTopic);


                    Log.d(TAG, "HandlSendThread: infors=" + infors);
                    MqttMessage tempInfora = new MqttMessage();
                    tempInfora.setQos(0);
                    tempInfora.setRetained(false);
                    System.out.println(tempInfora.isRetained() + "------ratained状态");
                    tempInfora.setPayload(infors.getBytes());
                    //String timea,String name, String orders,String prices
                    Log.d(TAG, "run:aa=" + myTopic + Urlinfor.getmUrlinfor().getShopInformationId() + Urlinfor.getmUrlinfor().getMdevicenums() + "_cmd");
                    client.publish(myTopic + Urlinfor.getmUrlinfor().getShopInformationId() + Urlinfor.getmUrlinfor().getMdevicenums() + "_cmd", tempInfora);

                } catch (Exception e) {
                    e.printStackTrace();
                }
                try {

                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

        }
    }


    public void handlOutmaterials(Integer menuType, Integer pin, Integer weighs, float speed, Integer times, Integer nums) {

        Log.d(TAG, "handlOutmaterials: menuType=" + menuType);
        Log.d(TAG, "handlOutmaterials: pin=" + pin);
        Log.d(TAG, "handlOutmaterials: weighs=" + weighs);
        Log.d(TAG, "handlOutmaterials: speed=" + speed);
        Log.d(TAG, "handlOutmaterials: times=" + times);
        Log.d(TAG, "handlOutmaterials: nums=" + nums);

        String pins = String.valueOf(pin);
        String weighses = String.valueOf(weighs);
        String menuTypes = String.valueOf(menuType);

        String keysa = String.valueOf(menuType) + "-" + String.valueOf(pin) + "-" + String.valueOf(weighs);

        Cursor cursorb = null;
        cursorb = mBdread.rawQuery("select * from outmaterials where menuType=? and  pin=? and weighs =? ", new String[]{menuTypes, pins, weighses});
        if ((cursorb != null && cursorb.getCount() > 0)) {
            ContentValues values = new ContentValues();

            // values.put("pin", pin );
            //  values.put("weighs", weighs );
            values.put("speed", speed);
            values.put("times", times);
            values.put("nums", nums);

            long updates = mBdwrite.update("outmaterials", values, " menuType=? and  pin=? and weighs =? ", new String[]{menuTypes, pins, weighses});
            Log.d("aaa", "handlOutmaterials update: " + updates);
        } else {
            ContentValues values = new ContentValues();
            values.put("menuType", menuType);
            values.put("pin", pin);
            values.put("weighs", weighs);
            values.put("speed", speed);
            values.put("times", times);
            values.put("nums", nums);


            long insert = mBdwrite.insert("outmaterials", null, values);
            Log.d("aaa", "handlOutmaterials insert: " + insert);
        }
        moutmaterialsSpeedMap.put(keysa, speed);
        moutmaterialsTimesMap.put(keysa, times);
        moutmaterialsNumsMap.put(keysa, nums);
    }

    public void findOutmaterials(Integer menuType, Integer pin, Integer weighs) {

        Log.d(TAG, "findOutmaterials: ==0");
        String pins = String.valueOf(pin);
        String weighses = String.valueOf(weighs);
        String menuTypes = String.valueOf(menuType);
        Log.d(TAG, "findOutmaterials: ==1");

        String keysa = menuTypes + "-" + pins + "-" + weighses;
        Cursor cursorb = null;
        cursorb = mBdread.rawQuery("select * from outmaterials where menuType=? and  pin=? and weighs =? ", new String[]{menuTypes, pins, weighses});

        Log.d(TAG, "findOutmaterials: ==2");
        if ((cursorb != null && cursorb.getCount() > 0)) {
            while (cursorb.moveToNext()) {


                Log.d(TAG, "findOutmaterials: ==2=0=" + cursorb.getCount());
                Log.d(TAG, "findOutmaterials: ==2=0==" + cursorb.getColumnIndex("pin"));

                int pina = cursorb.getInt(cursorb.getColumnIndex("pin"));
                Log.d(TAG, "findOutmaterials: ==2=1=" + pina);

                int weighsa = cursorb.getInt(cursorb.getColumnIndex("weighs"));
                Log.d(TAG, "findOutmaterials: ==2=2=" + weighsa);

                float speeda = cursorb.getFloat(cursorb.getColumnIndex("speed"));
                Log.d(TAG, "findOutmaterials: ==2=3=" + speeda);

                int timesa = cursorb.getInt(cursorb.getColumnIndex("times"));
                Log.d(TAG, "findOutmaterials: ==2=4=" + timesa);

                int numsa = cursorb.getInt(cursorb.getColumnIndex("nums"));
                Log.d(TAG, "findOutmaterials: ==3=" + numsa);

                moutmaterialsSpeedMap.put(keysa, speeda);
                moutmaterialsTimesMap.put(keysa, timesa);
                moutmaterialsNumsMap.put(keysa, numsa);
                Log.d(TAG, "findOutmaterials: ==4");
            }
        } else {
            Log.d(TAG, "findOutmaterials: ==5");

            moutmaterialsSpeedMap.put(keysa, (float) 100.0);
            moutmaterialsTimesMap.put(keysa, 0);
            moutmaterialsNumsMap.put(keysa, 0);
            Log.d(TAG, "findOutmaterials: ==6");
        }
    }

    public void handlMenumaterials(Integer sendMeus, Integer menuType, Integer nums) {
        String sendMeuses = String.valueOf(sendMeus);
        String menuTypees = String.valueOf(menuType);

        Cursor cursorb = null;
        cursorb = mBdread.rawQuery("select * from menumaterials where sendMeus=? and menuType =? ", new String[]{sendMeuses, menuTypees});
        if ((cursorb != null && cursorb.getCount() > 0)) {
            ContentValues values = new ContentValues();


            values.put("nums", nums);

            long updates = mBdwrite.update("menumaterials", values, "sendMeus=? and menuType =?", new String[]{sendMeuses, menuTypees});
            Log.d("aaa", "handlMenumaterials update: " + updates);
        } else {
            ContentValues values = new ContentValues();


            values.put("nums", nums);


            long insert = mBdwrite.insert("menumaterials", null, values);
            Log.d("aaa", "handlMenumaterials insert: " + insert);
        }
    }

    public void findMenumaterials(Integer sendMeus, Integer menuType) {
        String sendMeuses = String.valueOf(sendMeus);
        String menuTypees = String.valueOf(menuType);
        String keysa = sendMeuses + "-" + menuTypees;
        Cursor cursorb = null;
        cursorb = mBdread.rawQuery("select * from menumaterials where sendMeus=? and menuType =? ", new String[]{sendMeuses, menuTypees});
        if ((cursorb != null && cursorb.getCount() > 0)) {
            while (cursorb.moveToNext()) {
                int sendMeusa = cursorb.getInt(cursorb.getColumnIndex("sendMeus"));
                int menuTypea = cursorb.getInt(cursorb.getColumnIndex("menuType"));
                int numsa = cursorb.getInt(cursorb.getColumnIndex("nums"));
                mmenumaterialsNumsMap.put(keysa, numsa);
            }

        } else {
            mmenumaterialsNumsMap.put(keysa, 0);
        }
    }

    public String getMD5(String input) {
        try {
            // Create MD5 Hash
            MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
            digest.update(input.getBytes());
            byte messageDigest[] = digest.digest();

            // Create Hex String
            StringBuilder hexString = new StringBuilder();
            for (byte aMessageDigest : messageDigest) {
                String h = Integer.toHexString(0xFF & aMessageDigest);
                while (h.length() < 2) h = "0" + h;
                hexString.append(h);
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }


    private void sendRequestInitDeviceLogins() {


        new Thread(new Runnable() {

            @Override
            public void run() {
                String strUrl = Urlinfor.getmUrlinfor().getDevicelogins();
                Log.d("aaaaa", "strUrlstrUrl==" + strUrl);
                URL url = null;
                try {
                    long currentTime = System.currentTimeMillis();
                    String timeNow = new SimpleDateFormat("yyyy-MM-dd").format(currentTime);
                    url = new URL(strUrl);
                    HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
                    urlConn.setDoInput(true);
                    urlConn.setDoOutput(true);
                    urlConn.setRequestMethod("POST");
                    urlConn.setUseCaches(false);
                    urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    urlConn.setRequestProperty("Charset", "utf-8");
                    /*
                    if (urlConn instanceof HttpsURLConnection) {
                        try {
                            SSLContext sslContext = HttpsUtil.getSSLContextWithCer();

                            if (sslContext != null) {
                                SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
                                ((HttpsURLConnection) urlConn).setDefaultSSLSocketFactory(sslSocketFactory);

                            }
                        } catch (Exception e) {
                            e.printStackTrace();

                        }

                    }

                     */
                    urlConn.connect();

                    Log.d("aaaaa", "timeNow:==" + timeNow);
                    DataOutputStream dop = new DataOutputStream(urlConn.getOutputStream());
                    dop.writeBytes("device_no=" + Urlinfor.getmUrlinfor().getMdevicenums());
                    dop.writeBytes("&userName=" + m_userNames);
                    dop.writeBytes("&userPwd=" + m_userPwds);
                    dop.flush();
                    dop.close();
                    BufferedReader bufferReader = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
                    String result = "";
                    String readline = null;
                    while ((readline = bufferReader.readLine()) != null) {
                        result += readline;
                    }
                    bufferReader.close();
                    urlConn.disconnect();
                    //  String a = result.substring(0,result.length()/ 3);
                    //  String b= result.substring(result.length()/ 3,result.length()*2/ 3);
                    //  String c= result.substring(result.length()*2/ 3,result.length());
                    Log.d("aaaaa", "sendRequestInitDeviceLogins=abc=" + result);
                    //   Log.d("aaaaa", "minqq=aa=" + a);

                    // Log.d("aaaaa", "minqq=aaa=" + b);
                    // Log.d("aaaaa", "minqq=aaaaaa=" + c);

                    if (result.length() > 0) {
                        String resulta = result;

                        Message msg = new Message();
                        String str1;
                        str1 = resulta;
                        msg.what = SCREEN_LOGIN;
                        msg.obj = str1;
                        handlerLogins.sendMessage(msg);
                    } else {

                        Message msg = new Message();
                        String str1;
                        str1 = "";
                        msg.what = SCREEN_ERROR;
                        msg.obj = str1;
                        handlerLogins.sendMessage(msg);
                    }


                } catch (IOException e) {

                    Log.d("aaaaa", "222=");

                    e.printStackTrace();
                }

            }
        }).start();//这个start()方法不要忘记了

    }


    public void handlDeviceType() {
        FragmentTransaction fTransaction = fManager.beginTransaction();
        hideAllFragment(fTransaction);
        handlRadio();
        switch (m_select_types) {
            case R.id.homepage_nav_top_goods_radiobtn:
                if (homepage_nav_top_goods_radiobtn != null) {
                    homepage_nav_top_goods_radiobtn.setTextSize(mContext.getResources().getDimension(R.dimen.nav_menu_select));
                    homepage_nav_top_goods_radiobtn.setTypeface(null, Typeface.BOLD);
                }

                fTransaction.show(fg1);

                break;
            case R.id.homepage_nav_top_order_radiobtn:
                if (homepage_nav_top_order_radiobtn != null) {
                    homepage_nav_top_order_radiobtn.setTextSize(mContext.getResources().getDimension(R.dimen.nav_menu_select));
                    homepage_nav_top_order_radiobtn.setTypeface(null, Typeface.BOLD);
                }

                fTransaction.show(fg2);

                break;
            case R.id.homepage_nav_top_handl_out_radiobtn:

                if (homepage_nav_top_handl_out_radiobtn != null) {
                    homepage_nav_top_handl_out_radiobtn.setTextSize(mContext.getResources().getDimension(R.dimen.nav_menu_select));
                    homepage_nav_top_handl_out_radiobtn.setTypeface(null, Typeface.BOLD);
                }

                fTransaction.show(fg3);

                break;
            case R.id.homepage_nav_top_set_radiobtn:
                if (homepage_nav_top_set_radiobtn != null) {
                    homepage_nav_top_set_radiobtn.setTextSize(mContext.getResources().getDimension(R.dimen.nav_menu_select));
                    homepage_nav_top_set_radiobtn.setTypeface(null, Typeface.BOLD);
                }

                fTransaction.show(fg4);

                break;
        }
        fTransaction.commit();
        m_select_current_types = homepage_nav_top_radioGroup.getCheckedRadioButtonId();
    }


    public void handlPayOutData() {
        SpecifData typea = CartDatas.getCartDatas().getmSpecifData();
        String names = CartDatas.getCartDatas().getmNames();
        String typeOrder = CartDatas.getCartDatas().getmTypeOrder();
        String typeinfor = CartDatas.getCartDatas().getmTypeinfor();

        SlovmeData.getSlovmeData().setTypea(typea);
        int times = outData(typeOrder, typeinfor);
        try {

            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        if (mProducePopupView == null) {
            mProducePopupView = new ProducePopupView(mContext);
        }

        mProducePopupView.show();
        mProducePopupView.setNameInfor(names);
        mProducePopupView.setRunTime(times / 1000);

        mTimeSalesTime.sendEmptyMessageDelayed(TIME_SALES_DELATE, 1000);


    }


    public static void fullyRestartApp(Context context) {
        Log.d(TAG, "fullyRestartApp: ==11");
        Intent intent = context.getPackageManager()
                .getLaunchIntentForPackage(context.getPackageName());
        if (intent != null) {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            context.startActivity(intent);
        }
        // 结束当前进程
        android.os.Process.killProcess(android.os.Process.myPid());
        System.exit(0);
    }


    public void handlOutTeaMachine() {


//        mSerialPortTeaMachineUtils = new SerialPortTeaMachineUtils();
//        private SerialPort mSerialPortTeaMachinePort = null;
//        private byte[] mBuffTeaMachineStr = new byte[1024 * 3];
//        private int m_curTeaMachineLength = 0;
//        private ArrayList<Integer> moutTeaMachineArrys = new ArrayList<Integer>();

        if (moutTeaMachineArrys.size() > 0) {


            int nums = moutTeaMachineArrys.get(0);
            byte tempb = 0;
            byte[] buffer = new byte[1024];

            int space = 0;
            // ch[0]=0x01;
            buffer[0 + space] = 0x00;
            buffer[1 + space] = 0x68;
            buffer[2 + space] = (byte) m_curTeaMachineNumbers;
            buffer[3 + space] = 0x42;
            buffer[4 + space] = 0x41;

            buffer[5 + space] = 0x13;

            if (nums >= 2000) {
                buffer[6 + space] = 0x01;
            } else {
                buffer[6 + space] = 0x00;
            }

            buffer[7 + space] = 0x00;

            buffer[8 + space] = 0x01;
            buffer[9 + space] = 0x00;
            if (nums >= 2000) {
                nums = nums - 2000;
            } else {
                nums = nums - 1000;
            }
            buffer[10 + space] = (byte) nums;
            int crc = calculateCRC(buffer, 11);

            buffer[11 + space] = (byte) crc;
            buffer[12 + space] = (byte) (crc >> 8);

            String h = "";

            for (int i = 0; i <= 12; i++) {

                String temp = Integer.toHexString(buffer[i] & 0xFF);
                if (temp.length() == 1) {
                    temp = "0" + temp;
                }
                h = h + temp;

            }
            System.out.println("CRC16-h=1=" + h);


            byte[] arry1 = {0x01};


            byte[] arry2 = {0x04};

            // 定义替换规则（rel -> new）
            byte[] rel0 = {0x00};
            byte[] rel1 = {0x01};
            byte[] rel2 = {0x02};
            byte[] rel3 = {0x03};
            byte[] rel4 = {0x04};
            byte[] rel5 = {0x0A};
            byte[] rel6 = {0x0D};
            byte[] rel7 = {0x10};
            byte[] rel8 = {0x17};

            byte[] new0 = {0x10, 0x40};
            byte[] new1 = {0x10, 0x41};
            byte[] new2 = {0x10, 0x42};
            byte[] new3 = {0x10, 0x43};
            byte[] new4 = {0x10, 0x44};
            byte[] new5 = {0x10, 0x4A};
            byte[] new6 = {0x10, 0x4D};
            byte[] new7 = {0x10, 0x50};
            byte[] new8 = {0x10, 0x57};

            byte[] arrys = new byte[13];
            System.arraycopy(buffer, 0, arrys, 0, 13);

            arrys = replaceInforBytes(arrys, rel7, new7);
            arrys = replaceInforBytes(arrys, rel8, new8);
            arrys = replaceInforBytes(arrys, rel0, new0);
            arrys = replaceInforBytes(arrys, rel1, new1);
            arrys = replaceInforBytes(arrys, rel2, new2);
            arrys = replaceInforBytes(arrys, rel3, new3);
            arrys = replaceInforBytes(arrys, rel4, new4);
            arrys = replaceInforBytes(arrys, rel5, new5);
            arrys = replaceInforBytes(arrys, rel6, new6);


            byte[] arrya = new byte[arry1.length + arrys.length + arry2.length];
            System.arraycopy(arry1, 0, arrya, 0, arry1.length);
            System.arraycopy(arrys, 0, arrya, arry1.length, arrys.length);
            System.arraycopy(arry2, 0, arrya, arry1.length + arrys.length, arry2.length);

            h = "";

            for (int i = 0; i < arrya.length; i++) {

                String temp = Integer.toHexString(arrya[i] & 0xFF);
                if (temp.length() == 1) {
                    temp = "0" + temp;
                }
                h = h + temp;

            }
            System.out.println("CRC16-h=2=" + h);

//            byte[] arryb =   handlTransformation(arrya);
//            h = "";
//
//            for (int i = 0; i < arryb.length; i++) {
//
//                String temp = Integer.toHexString(arryb[i] & 0xFF);
//                if (temp.length() == 1) {
//                    temp = "0" + temp;
//                }
//                h = h + temp;
//
//            }
//            System.out.println( "CRC16-h=3="+ h);
            misSend = true;
            if (mSerialPortTeaMachinePort != null) {
                m_curTeaMachineLength = 0;
                m_curTeaMachineNumbers++;
                if (m_curTeaMachineNumbers >= 255) {
                    m_curTeaMachineNumbers = 0;
                }
                mBuffTeaMachineStr = new byte[1024 * 3];
                mSerialPortTeaMachineUtils.sendByteSerialLenPort(arrya, 0, arrya.length);
            }

            if (mTeaMachineWaitViews == null) {
                mTeaMachineWaitViews = new TeaMachineWaitViews(mContext);
            }
            mTeaMachineWaitViews.show();
            if (mTimeFindRunSatus != null) {
                mTimeFindRunSatus.sendEmptyMessageDelayed(1002, 800);
            }


            mTimeSecondView.sendEmptyMessageDelayed(TIME_SECOND_VIEW,3000);

        }


    }

    public int calculateCRC(byte[] data, int dataLength) {
        int checkSum = 0xFFFF; // 初始值

        for (int i = 0; i < dataLength; i++) {
            byte b = data[i];
            // 注意：Java 的 byte 是有符号的，需要转换为无符号的 0-255
            int unsignedByte = b & 0xFF;
            // 计算 CRC
            checkSum = (checkSum >>> 8) ^ crcPolynomTable[(checkSum ^ unsignedByte) & 0xFF];
        }

        return checkSum & 0xFFFF; // 确保返回 16 位无符号值


    }

    /**
     * 替换 byte[] 中的目标字节序列
     *
     * @param source      原始字节数组
     * @param target      要替换的目标字节（单字节）
     * @param replacement 替换后的字节序列
     * @return 替换后的新字节数组
     */
    public static byte[] replaceInforBytes(byte[] source, byte[] target, byte[] replacement) {
        if (target.length != 1) {
            throw new IllegalArgumentException("Target must be a single byte");
        }

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        for (byte b : source) {
            if (b == target[0]) {
                outputStream.write(replacement, 0, replacement.length);
            } else {
                outputStream.write(b);
            }
        }
        return outputStream.toByteArray();
    }

    public static String bytesToHex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02X", b));
        }
        return sb.toString();
    }

    public byte[] handlTransformation(byte[] data) {
        byte[] mSerialByteArray = new byte[0];

        byte[] serialData = data;
// 定义要删除的字节
        byte[] arry1 = {0x01};
        byte[] arry2 = {0x04};

// 定义替换目标字节
        byte[] rel0 = {0x00};
        byte[] rel1 = {0x01};
        byte[] rel2 = {0x02};
        byte[] rel3 = {0x03};
        byte[] rel4 = {0x04};
        byte[] rel5 = {0x0A};
        byte[] rel6 = {0x0D};
        byte[] rel7 = {0x10};
        byte[] rel8 = {0x17};

// 定义替换内容
        byte[] new0 = {0x10, 0x40};
        byte[] new1 = {0x10, 0x41};
        byte[] new2 = {0x10, 0x42};
        byte[] new3 = {0x10, 0x43};
        byte[] new4 = {0x10, 0x44};
        byte[] new5 = {0x10, 0x4A};
        byte[] new6 = {0x10, 0x4D};
        byte[] new7 = {0x10, 0x50};
        byte[] new8 = {0x10, 0x57};
        // 删除 arry1 和 arry2
        serialData = removeBytes(serialData, arry1);
        serialData = removeBytes(serialData, arry2);

        // 追加到成员变量
        mSerialByteArray = concatBytes(mSerialByteArray, serialData);

        // 执行替换操作（注意顺序与Qt代码一致）
        mSerialByteArray = replaceBytes(mSerialByteArray, new0, rel0);
        mSerialByteArray = replaceBytes(mSerialByteArray, new1, rel1);
        mSerialByteArray = replaceBytes(mSerialByteArray, new2, rel2);
        mSerialByteArray = replaceBytes(mSerialByteArray, new3, rel3);
        mSerialByteArray = replaceBytes(mSerialByteArray, new4, rel4);
        mSerialByteArray = replaceBytes(mSerialByteArray, new5, rel5);
        mSerialByteArray = replaceBytes(mSerialByteArray, new6, rel6);
        mSerialByteArray = replaceBytes(mSerialByteArray, new7, rel7);
        mSerialByteArray = replaceBytes(mSerialByteArray, new8, rel8);

        // 处理完成后可以使用 mSerialByteArray
        // 例如转换为十六进制字符串打印
        String hexString = bytesToHex(mSerialByteArray);
        Log.d("SerialData", hexString);
        return mSerialByteArray;
    }

    // 删除指定字节序列
    public static byte[] removeBytes(byte[] source, byte[] toRemove) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        int pos = 0;

        while (pos < source.length) {
            boolean match = true;
            for (int i = 0; i < toRemove.length; i++) {
                if (pos + i >= source.length || source[pos + i] != toRemove[i]) {
                    match = false;
                    break;
                }
            }

            if (match) {
                pos += toRemove.length;
            } else {
                outputStream.write(source[pos]);
                pos++;
            }
        }

        return outputStream.toByteArray();
    }

    // 替换字节序列
    public static byte[] replaceBytes(byte[] source, byte[] from, byte[] to) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        int pos = 0;

        while (pos < source.length) {
            boolean match = true;
            for (int i = 0; i < from.length; i++) {
                if (pos + i >= source.length || source[pos + i] != from[i]) {
                    match = false;
                    break;
                }
            }

            if (match) {
                outputStream.write(to, 0, to.length);
                pos += from.length;
            } else {
                outputStream.write(source[pos]);
                pos++;
            }
        }

        return outputStream.toByteArray();
    }

    // 合并字节数组
    public static byte[] concatBytes(byte[]... arrays) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            for (byte[] array : arrays) {
                outputStream.write(array);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return outputStream.toByteArray();
    }

    public boolean containsByte(byte[] data, byte target) {
        for (byte b : data) {
            if (b == target) {
                return true;
            }
        }
        return false;
    }

    public void findTeaMachine() {
        if (moutTeaMachineArrys.size() > 0) {
            int nums = moutTeaMachineArrys.get(0);
            byte tempb = 0;
            byte[] buffer = new byte[1024];

            int space = 0;
            // ch[0]=0x01;
            buffer[0 + space] = 0x00;
            buffer[1 + space] = 0x6C;
            buffer[2 + space] = (byte) m_curTeaMachineNumbers;
            buffer[3 + space] = 0x42;
            buffer[4 + space] = 0x41;

            buffer[5 + space] = 0x01;

            buffer[6 + space] = 0x00;

            buffer[7 + space] = 0x00;

            buffer[8 + space] = 0x00;
            buffer[9 + space] = 0x00;

            int crc = calculateCRC(buffer, 10);

            buffer[10 + space] = (byte) crc;
            buffer[11 + space] = (byte) (crc >> 8);

            String h = "";

            for (int i = 0; i <= 11; i++) {

                String temp = Integer.toHexString(buffer[i] & 0xFF);
                if (temp.length() == 1) {
                    temp = "0" + temp;
                }
                h = h + temp;

            }
            System.out.println("handlTeaMachine-h=1=" + h);


            byte[] arry1 = {0x01};


            byte[] arry2 = {0x04};

            // 定义替换规则（rel -> new）
            byte[] rel0 = {0x00};
            byte[] rel1 = {0x01};
            byte[] rel2 = {0x02};
            byte[] rel3 = {0x03};
            byte[] rel4 = {0x04};
            byte[] rel5 = {0x0A};
            byte[] rel6 = {0x0D};
            byte[] rel7 = {0x10};
            byte[] rel8 = {0x17};

            byte[] new0 = {0x10, 0x40};
            byte[] new1 = {0x10, 0x41};
            byte[] new2 = {0x10, 0x42};
            byte[] new3 = {0x10, 0x43};
            byte[] new4 = {0x10, 0x44};
            byte[] new5 = {0x10, 0x4A};
            byte[] new6 = {0x10, 0x4D};
            byte[] new7 = {0x10, 0x50};
            byte[] new8 = {0x10, 0x57};

            byte[] arrys = new byte[12];
            System.arraycopy(buffer, 0, arrys, 0, 12);

            arrys = replaceInforBytes(arrys, rel7, new7);
            arrys = replaceInforBytes(arrys, rel8, new8);
            arrys = replaceInforBytes(arrys, rel0, new0);
            arrys = replaceInforBytes(arrys, rel1, new1);
            arrys = replaceInforBytes(arrys, rel2, new2);
            arrys = replaceInforBytes(arrys, rel3, new3);
            arrys = replaceInforBytes(arrys, rel4, new4);
            arrys = replaceInforBytes(arrys, rel5, new5);
            arrys = replaceInforBytes(arrys, rel6, new6);


            byte[] arrya = new byte[arry1.length + arrys.length + arry2.length];
            System.arraycopy(arry1, 0, arrya, 0, arry1.length);
            System.arraycopy(arrys, 0, arrya, arry1.length, arrys.length);
            System.arraycopy(arry2, 0, arrya, arry1.length + arrys.length, arry2.length);

            h = "";

            for (int i = 0; i < arrya.length; i++) {

                String temp = Integer.toHexString(arrya[i] & 0xFF);
                if (temp.length() == 1) {
                    temp = "0" + temp;
                }
                h = h + temp;

            }
            System.out.println("handlTeaMachine-h=2=" + h);

            if (mSerialPortTeaMachinePort != null) {

                m_curTeaMachineNumbers++;
                if (m_curTeaMachineNumbers >= 255) {
                    m_curTeaMachineNumbers = 0;
                }
                m_curTeaMachineLength = 0;
                mBuffTeaMachineStr = new byte[1024 * 3];
                mSerialPortTeaMachineUtils.sendByteSerialLenPort(arrya, 0, arrya.length);
            }
        }

    }

    public void stopTeaMachine() {
        if (moutTeaMachineArrys.size() > 0) {
            int nums = moutTeaMachineArrys.get(0);
            byte tempb = 0;
            byte[] buffer = new byte[1024];

            int space = 0;
            // ch[0]=0x01;
            buffer[0 + space] = 0x00;
            buffer[1 + space] = 0x68;
            buffer[2 + space] = (byte) m_curTeaMachineNumbers;
            buffer[3 + space] = 0x42;
            buffer[4 + space] = 0x41;

            buffer[5 + space] = 0x0B;

            buffer[6 + space] = 0x00;

            buffer[7 + space] = 0x00;

            buffer[8 + space] = 0x00;
            buffer[9 + space] = 0x00;

            int crc = calculateCRC(buffer, 10);

            buffer[10 + space] = (byte) crc;
            buffer[11 + space] = (byte) (crc >> 8);

            String h = "";

            for (int i = 0; i <= 11; i++) {

                String temp = Integer.toHexString(buffer[i] & 0xFF);
                if (temp.length() == 1) {
                    temp = "0" + temp;
                }
                h = h + temp;

            }
            System.out.println("handlTeaMachine-h=1=" + h);


            byte[] arry1 = {0x01};


            byte[] arry2 = {0x04};

            // 定义替换规则（rel -> new）
            byte[] rel0 = {0x00};
            byte[] rel1 = {0x01};
            byte[] rel2 = {0x02};
            byte[] rel3 = {0x03};
            byte[] rel4 = {0x04};
            byte[] rel5 = {0x0A};
            byte[] rel6 = {0x0D};
            byte[] rel7 = {0x10};
            byte[] rel8 = {0x17};

            byte[] new0 = {0x10, 0x40};
            byte[] new1 = {0x10, 0x41};
            byte[] new2 = {0x10, 0x42};
            byte[] new3 = {0x10, 0x43};
            byte[] new4 = {0x10, 0x44};
            byte[] new5 = {0x10, 0x4A};
            byte[] new6 = {0x10, 0x4D};
            byte[] new7 = {0x10, 0x50};
            byte[] new8 = {0x10, 0x57};

            byte[] arrys = new byte[12];
            System.arraycopy(buffer, 0, arrys, 0, 12);

            arrys = replaceInforBytes(arrys, rel7, new7);
            arrys = replaceInforBytes(arrys, rel8, new8);
            arrys = replaceInforBytes(arrys, rel0, new0);
            arrys = replaceInforBytes(arrys, rel1, new1);
            arrys = replaceInforBytes(arrys, rel2, new2);
            arrys = replaceInforBytes(arrys, rel3, new3);
            arrys = replaceInforBytes(arrys, rel4, new4);
            arrys = replaceInforBytes(arrys, rel5, new5);
            arrys = replaceInforBytes(arrys, rel6, new6);


            byte[] arrya = new byte[arry1.length + arrys.length + arry2.length];
            System.arraycopy(arry1, 0, arrya, 0, arry1.length);
            System.arraycopy(arrys, 0, arrya, arry1.length, arrys.length);
            System.arraycopy(arry2, 0, arrya, arry1.length + arrys.length, arry2.length);

            h = "";

            for (int i = 0; i < arrya.length; i++) {

                String temp = Integer.toHexString(arrya[i] & 0xFF);
                if (temp.length() == 1) {
                    temp = "0" + temp;
                }
                h = h + temp;

            }
            System.out.println("handlTeaMachine-h=2=" + h);

            if (mSerialPortTeaMachinePort != null) {

                m_curTeaMachineNumbers++;
                if (m_curTeaMachineNumbers >= 255) {
                    m_curTeaMachineNumbers = 0;
                }
                m_curTeaMachineLength = 0;
                mBuffTeaMachineStr = new byte[1024 * 3];
                mSerialPortTeaMachineUtils.sendByteSerialLenPort(arrya, 0, arrya.length);
            }
        }

    }

    public void cancelTeaMachine() {

        stopTeaMachine();
        moutTeaMachineArrys.clear();

        if (mTimeFindRunSatus != null) {
            mTimeFindRunSatus.removeMessages(1002);

        }


    }


    //清洗处理
    class CleanRunThread extends Thread {
        @Override
        public void run() {

            if (CleanStatusRecord.getmUrlinfor().getmCleanRunStatus() == 1) {
                return;
            }
            if (CleanStatusRecord.getmUrlinfor().getmCleanTopStatus() == 1) {
                return;
            }

            DebugUtils.printLogInfo("");
            HashMap<String, CleanRunRecord> cleanRunRecordMap = CleanConfigRecord.getmUrlinfor().getmCleanRunRecordMap();
            HashMap<String, CleanDataRecord> cleanDataRecordMap = CleanDatabaseRecord.getmUrlinfor().getmCleanRunRecordMap();
            DebugUtils.printDebugInfo(cleanRunRecordMap.toString());
            DebugUtils.printDebugInfo(cleanDataRecordMap.toString());
            SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            SimpleDateFormat formatter2 = new SimpleDateFormat("yyyy-MM-dd");
            long timestamps = System.currentTimeMillis();
            Date curDate1 = new Date(timestamps);//获取当前时间
            String str1 = formatter1.format(curDate1);
            String str2 = formatter2.format(curDate1);
            String strnew2 = str2 + " 00:00:00";


            for (Map.Entry<String, CleanRunRecord> entry : cleanRunRecordMap.entrySet()) {

                DebugUtils.printDebugInfo("");
                String runName = entry.getKey();
                CleanRunRecord record = entry.getValue();
                DebugUtils.printDebugInfo(runName);
                String detectNew = record.getDetectNew();

                if (detectNew == null || detectNew.length() <= 0) {
                    detectNew = "0";
                }
                DebugUtils.printDebugInfo(detectNew);
                DebugUtils.printDebugInfo("");
                if (Integer.parseInt(detectNew) == 1) {
                    DebugUtils.printDebugInfo("");
                    Integer detectIntervalNew = 1;
                    DebugUtils.printDebugInfo("");
                    if (record.getDetectIntervalNew().length() > 0) {
                        detectIntervalNew = Integer.parseInt(record.getDetectIntervalNew());
                    }
                    DebugUtils.printDebugInfo("");
                    String detectStartNew = record.getDetectStartNew();
                    String detectEndNew = record.getDetectEndNew();
                    Integer enforce = 0;
                    DebugUtils.printDebugInfo("");
                    if (record.getEnforce().length() > 0) {
                        enforce = Integer.parseInt(record.getEnforce());
                    }
                    DebugUtils.printDebugInfo(cleanDataRecordMap.toString());
                    CleanDataRecord recordb = cleanDataRecordMap.get(runName);
                    DebugUtils.printDebugInfo("");
                    if (recordb.getDetectStartNew().length() > 0) {
                        DebugUtils.printDebugInfo("");
                        if (recordb.getDetectEndNew().length() > 0) {
                            DebugUtils.printDebugInfo("");
                            String itema = str2 + " " + detectStartNew;
                            String itemb = str2 + " " + detectEndNew;
                            DebugUtils.printDebugInfo(itema);
                            DebugUtils.printDebugInfo(itemb);
                            DebugUtils.printDebugInfo("");
                            String time1 = recordb.getDetectStartNew() + " " + detectStartNew;
                            String time2 = recordb.getDetectEndNew() + " " + detectEndNew;
                            DebugUtils.printDebugInfo(time1);
                            DebugUtils.printDebugInfo(time2);
                            String pattern = "yyyy-MM-dd HH:mm:ss";
                            DebugUtils.printDebugInfo("");
                            //  timestamps;

                            long timestamp1 = convertStringToTimestamp(itema, pattern);
                            DebugUtils.printDebugInfo(String.valueOf(timestamp1));
                            long timestamp2 = convertStringToTimestamp(itemb, pattern);
                            DebugUtils.printDebugInfo(String.valueOf(timestamp2));
                            long timestampOld1 = convertStringToTimestamp(time1, pattern);
                            DebugUtils.printDebugInfo(String.valueOf(timestampOld1));
                            long timestampOld2 = convertStringToTimestamp(time2, pattern);
                            DebugUtils.printDebugInfo(String.valueOf(timestampOld2));
                            timestampOld1 += detectIntervalNew * 24 * 60 * 60 * 1000;
                            timestampOld2 += detectIntervalNew * 24 * 60 * 60 * 1000;
                            DebugUtils.printDebugInfo("");
                            if (enforce == 1) {
                                DebugUtils.printDebugInfo("");
                                if (timestamps >= timestampOld2) {
                                    DebugUtils.printDebugInfo("");
                                    CleanStatusRecord.getmUrlinfor().setCleantimeId(runName);
                                    CleanStatusRecord.getmUrlinfor().setmCleanTopStatus(1);
                                    CleanStatusRecord.getmUrlinfor().setCleanRunRecord(record);
                                    CleanStatusRecord.getmUrlinfor().setCleanNames(record.getClearName());
                                    Message msg = new Message();
                                    msg.what = 3;  //消息(一个整型值)
                                    mTimeShowHandler.sendMessage(msg);
                                    return;


                                } else {
                                    DebugUtils.printDebugInfo("");
                                    if (timestamps >= timestampOld1 && timestamps <= timestampOld2) {
                                        DebugUtils.printDebugInfo("");
                                        CleanStatusRecord.getmUrlinfor().setCleantimeId(runName);
                                        CleanStatusRecord.getmUrlinfor().setmCleanTopStatus(1);
                                        CleanStatusRecord.getmUrlinfor().setCleanRunRecord(record);
                                        CleanStatusRecord.getmUrlinfor().setCleanNames(record.getClearName());
                                        Message msg = new Message();
                                        msg.what = 2;  //消息(一个整型值)
                                        mTimeShowHandler.sendMessage(msg);
                                        return;

                                    }
                                }


                            } else {
                                DebugUtils.printDebugInfo("");
                                if (timestamps >= timestampOld1) {
                                    DebugUtils.printDebugInfo("");
                                    CleanStatusRecord.getmUrlinfor().setCleantimeId(runName);
                                    CleanStatusRecord.getmUrlinfor().setmCleanTopStatus(1);
                                    CleanStatusRecord.getmUrlinfor().setCleanRunRecord(record);
                                    CleanStatusRecord.getmUrlinfor().setCleanNames(record.getClearName());
                                    Message msg = new Message();
                                    msg.what = 2;  //消息(一个整型值)
                                    mTimeShowHandler.sendMessage(msg);
                                    return;

                                }

                            }

                        } else {
                            DebugUtils.printDebugInfo("");
                            String itema = str2 + " " + detectStartNew;
                            String itemb = str2 + " " + detectEndNew;
                            String dateStr = itema;
                            String pattern = "yyyy-MM-dd HH:mm:ss";
                            dateStr = itema;
                            long timestamp1 = convertStringToTimestamp(dateStr, pattern);
                            dateStr = itemb;
                            long timestamp2 = convertStringToTimestamp(dateStr, pattern);
                            DebugUtils.printDebugInfo("");
                            if (enforce == 1) {
                                DebugUtils.printDebugInfo("");
                                if (timestamps >= timestamp2) {
                                    DebugUtils.printDebugInfo("");
                                    CleanStatusRecord.getmUrlinfor().setCleantimeId(runName);
                                    CleanStatusRecord.getmUrlinfor().setmCleanTopStatus(1);
                                    CleanStatusRecord.getmUrlinfor().setCleanRunRecord(record);
                                    CleanStatusRecord.getmUrlinfor().setCleanNames(record.getClearName());
                                    Message msg = new Message();
                                    msg.what = 3;  //消息(一个整型值)
                                    mTimeShowHandler.sendMessage(msg);
                                    return;


                                }
                                if (timestamps >= timestamp1 && timestamps <= timestamp2) {
                                    DebugUtils.printDebugInfo("");
                                    CleanStatusRecord.getmUrlinfor().setCleantimeId(runName);
                                    CleanStatusRecord.getmUrlinfor().setmCleanTopStatus(1);
                                    CleanStatusRecord.getmUrlinfor().setCleanRunRecord(record);
                                    CleanStatusRecord.getmUrlinfor().setCleanNames(record.getClearName());
                                    Message msg = new Message();
                                    msg.what = 2;  //消息(一个整型值)
                                    mTimeShowHandler.sendMessage(msg);
                                    return;

                                }
                            } else {
                                DebugUtils.printDebugInfo("");
                                if (timestamps >= timestamp1) {
                                    DebugUtils.printDebugInfo("");
                                    CleanStatusRecord.getmUrlinfor().setCleantimeId(runName);
                                    CleanStatusRecord.getmUrlinfor().setmCleanTopStatus(1);
                                    CleanStatusRecord.getmUrlinfor().setCleanRunRecord(record);
                                    CleanStatusRecord.getmUrlinfor().setCleanNames(record.getClearName());
                                    Message msg = new Message();
                                    msg.what = 2;  //消息(一个整型值)
                                    mTimeShowHandler.sendMessage(msg);
                                    return;

                                }
                            }

                        }


                    } else {
                        DebugUtils.printDebugInfo("");
                        String itema = str2 + " " + detectStartNew;
                        String itemb = str2 + " " + detectEndNew;
                        String dateStr = itema;
                        String pattern = "yyyy-MM-dd HH:mm:ss";
                        dateStr = itema;
                        long timestamp1 = convertStringToTimestamp(dateStr, pattern);
                        dateStr = itemb;
                        long timestamp2 = convertStringToTimestamp(dateStr, pattern);
                        DebugUtils.printDebugInfo("");
                        if (enforce == 1) {
                            DebugUtils.printDebugInfo("");
                            if (timestamps >= timestamp2) {
                                DebugUtils.printDebugInfo("");
                                CleanStatusRecord.getmUrlinfor().setCleantimeId(runName);
                                CleanStatusRecord.getmUrlinfor().setmCleanTopStatus(1);
                                CleanStatusRecord.getmUrlinfor().setCleanRunRecord(record);
                                CleanStatusRecord.getmUrlinfor().setCleanNames(record.getClearName());
                                Message msg = new Message();
                                msg.what = 3;  //消息(一个整型值)
                                mTimeShowHandler.sendMessage(msg);
                                return;


                            }
                            if (timestamps >= timestamp1 && timestamps <= timestamp2) {
                                DebugUtils.printDebugInfo("");
                                CleanStatusRecord.getmUrlinfor().setCleantimeId(runName);
                                CleanStatusRecord.getmUrlinfor().setmCleanTopStatus(1);
                                CleanStatusRecord.getmUrlinfor().setCleanRunRecord(record);
                                CleanStatusRecord.getmUrlinfor().setCleanNames(record.getClearName());
                                Message msg = new Message();
                                msg.what = 2;  //消息(一个整型值)
                                mTimeShowHandler.sendMessage(msg);
                                return;

                            }
                        } else {
                            DebugUtils.printDebugInfo("");
                            if (timestamps >= timestamp1) {
                                DebugUtils.printDebugInfo("");
                                CleanStatusRecord.getmUrlinfor().setCleantimeId(runName);
                                CleanStatusRecord.getmUrlinfor().setmCleanTopStatus(1);
                                CleanStatusRecord.getmUrlinfor().setCleanRunRecord(record);
                                CleanStatusRecord.getmUrlinfor().setCleanNames(record.getClearName());
                                Message msg = new Message();
                                msg.what = 2;  //消息(一个整型值)
                                mTimeShowHandler.sendMessage(msg);
                                return;

                            }
                        }


                    }


                }

            }


        }
    }


    public long convertStringToTimestamp(String dateString, String pattern) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(pattern, Locale.getDefault());
            Date date = sdf.parse(dateString);
            return date.getTime();  // 返回毫秒级时间戳
        } catch (Exception e) {
            e.printStackTrace();
            return 0L;  // 转换失败返回0或其他默认值
        }
    }


    public void updatecleanRecord() {
        ContentValues values = new ContentValues();

        values.put("cleanStartTime", CleanStatusRecord.getmUrlinfor().getDetectStartNew());
        values.put("cleanEndTime", CleanStatusRecord.getmUrlinfor().getDetectEndNew());

        CleanDataRecord cleanDataRecord = CleanDatabaseRecord.getmUrlinfor().getCleanRunRecordMapIndex(CleanStatusRecord.getmUrlinfor().getCleantimeId());
        cleanDataRecord.setDetectStartNew(CleanStatusRecord.getmUrlinfor().getDetectStartNew());
        cleanDataRecord.setDetectEndNew(CleanStatusRecord.getmUrlinfor().getDetectEndNew());
        CleanDatabaseRecord.getmUrlinfor().addCleanRunRecordMap(CleanStatusRecord.getmUrlinfor().getCleantimeId(), cleanDataRecord);
        long insert = mBdwrite.update("cleanRecord", values, "ids=? ", new String[]{(CleanStatusRecord.getmUrlinfor().getCleantimeId())});

    }


    public void findDir() {
        Log.d(TAG, "findDir: =0");
        if (mdirName.length() > 0) {
            Log.d(TAG, "findDir: =1");
            File file = new File(mdirName);
            if (file.exists()) {
                Log.d(TAG, "findDir: =2");
                getFiles(mdirName);
            }

        }

    }
    private void getFiles(String path) {
        Log.d("aaa", "getFiles: path==" + path);
        File folder = new File(path);
        //  File[] allFiles = new File(path).listFiles();

        if (folder.exists() && folder.isDirectory()) {
            Log.d("aaa", "getFiles: path=1=" + path);

            File[] allFiles = folder.listFiles();
            Log.d("aaa", "getFiles: allFiles.length==" + allFiles.length);
            for (int i = 0; i < allFiles.length; i++) {
                File file = allFiles[i];
                Log.d("aaa", "getFiles: file.getAbsolutePath()==" + file.getAbsolutePath());

                if (file.isFile()) {
                    String items1 = file.getAbsolutePath();
                    Log.d("aaa", "getFiles: items1==" + items1);

                    String items2 = items1.toLowerCase();
                    String subString = "mp4";
                    String subString1 = subString.toLowerCase();
                    if (items2.contains(subString1)) {
                        msetcontents.add(file.getAbsolutePath());
                    }
//                    subString = "png";
//                    subString1 = subString.toLowerCase();
//                    if (items2.contains(subString1)) {
//                        msetcontents.add(file.getAbsolutePath());
//                    }
//                    subString = "jpg";
//                    subString1 = subString.toLowerCase();
//                    if (items2.contains(subString1)) {
//                        msetcontents.add(file.getAbsolutePath());
//                    }
                } else if (!file.getAbsolutePath().contains(".thumnail")) {
                    // getFiles( file.getAbsolutePath());
                }
            }

        }
        Log.d("aaa", "getFiles: path=2=" + path);


        Log.d("aaa", "getFiles: msetcontents.size()==" + msetcontents.size());
    }



    public void handlPlayPath() {
//        mCustomVideoView.stopPlayback();
//        mCustomVideoView.clearFocus();
//        mCustomVideoView.setVideoURI(Uri.parse("android.resource://com.example.controltimeviewr.controltimeview/" + R.raw.demo));
//
//        mCustomVideoView.start();
//        if(true){
//            return;
//        }
        Log.d(TAG, "handlPlayPath: =0");
        if (msetcontents.size() > 0) {
            Log.d(TAG, "handlPlayPath: =1");
            if (mindex >= msetcontents.size()) {
                Log.d(TAG, "handlPlayPath: =2");
                mindex = 0;
            }
            Log.d(TAG, "handlPlayPath: =mindex=" + String.valueOf(mindex));
            int indexa = 0;
            boolean isHave = false;
            for (String value : msetcontents) {
                Log.d("aaaaa", "onCompletion =mdirName + value=a=" + value);
                File filea = new File(value);
                if (mindex == indexa && filea.exists()) {
                    Log.d("aaaaa", "onCompletion =mdirName + value=" + value);
                    if(mCustomVideoView != null ){
                        mCustomVideoView.stopPlayback();
                        mCustomVideoView.clearFocus();
                        mCustomVideoView.setVideoPath(value);
                        mCustomVideoView.start();
                    }

                    isHave = true;
                    break;
                }
                indexa++;
            }

            if (!isHave) {
                Log.d(TAG, "handlPlayPath: +temnp=3");
                if(mCustomVideoView != null ) {
                    mCustomVideoView.stopPlayback();
                    mCustomVideoView.clearFocus();
                    // String fileName = getResources().getResourceName(R.raw.demo);
                    mCustomVideoView.setVideoURI(Uri.parse("android.resource://com.example.fruitjuice/" + R.raw.demo));
                    //  Log.d("aaa", "handlPlayPath: fileName=="+fileName);
                    //  mCustomVideoView.setVideoURI(Uri.parse(fileName));

                    mCustomVideoView.start();
                }
            } else {
                mindex++;
            }

        } else {
            Log.d(TAG, "handlPlayPath: =3");
            if(mCustomVideoView != null ) {
                mCustomVideoView.stopPlayback();
                mCustomVideoView.clearFocus();
                // String fileName = getResources().getResourceName(R.raw.demo);
                mCustomVideoView.setVideoURI(Uri.parse("android.resource://com.example.bgmachine.bgmachine/" + R.raw.demo));
                //  Log.d("aaa", "handlPlayPath: fileName=="+fileName);
                //  mCustomVideoView.setVideoURI(Uri.parse(fileName));

                mCustomVideoView.start();
            }
        }
    }


    @Override
    protected void onStart() {
        super.onStart();
        findDir();
        handlPlayPath();
    }
}
